# CockroachDB > This file is very large and may be truncated. For an index of this content, please refer to https://docs.cockroachlabs.com/llms.txt instead. # Admission Control Source: https://docs.cockroachlabs.com/docs/continuum/admission-control # Cockroach Aegis Agentic Ecosystem Source: https://docs.cockroachlabs.com/docs/continuum/aegis-agentic-ecosystem > [!NOTE] > > **This feature is in [private preview](/docs/releases/cockroachdb-feature-availability)** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. Cockroach Aegis exposes its analysis of your CockroachDB clusters to your own AI agents through a hosted [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) endpoint. An agent such as Claude Code or Codex CLI can retrieve Aegis's cluster and workload reports and its recommendations, and combine that CockroachDB-specific context with application code, metrics, and incident information from your other tools. Benefits of connecting your agent to Aegis include: * Analyzed context. Your agent receives the reports and recommendations that Aegis's CockroachDB-specific agent harness has already produced from its check-ins and investigations, rather than raw database signals. * A standard integration. The endpoint uses MCP over HTTP with OAuth, so it works with any MCP client that supports remote servers. * No cluster access. The Aegis MCP endpoint doesn't interact with your cluster or issue any queries to it, even read-only ones. It gives your agent recommendations and reports that Aegis has already generated, and lets it update recommendation status in Aegis. * Persistent context. [Reports and recommendations](/docs/continuum/aegis-overview#reports-and-recommendations) are stored in the hosted Aegis service, so your agent can retrieve them at any time, including when Aegis cannot currently reach the cluster. This page describes: * Ways to [bring your own agent](#bring-your-own-agent) to Aegis. * How to [connect through MCP](#connect-through-mcp), including setup for [Claude Code](#claude-code-setup) and [Codex CLI](#codex-cli-setup), how to [verify the connection](#verify-the-mcp-connection), and the [available operations](#available-operations). * How to [analyze a workload change through MCP](#analyze-a-workload-change-through-mcp). For information about how Aegis works, see [Cockroach Aegis Overview](/docs/continuum/aegis-overview). For information about connecting a cluster, permissions, and data handling, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). ## Bring your own agent Connect your AI agents to Aegis to use its cluster reports, recommendations, and other context in your existing workflows. For example, you can use Aegis context to: * Review query and schema changes alongside the workload report. * Investigate a capacity problem using the cluster's configuration and resource observations. * Assess cluster health when an incident alert arrives, using Aegis reports and recommendations. * Build an event timeline with Aegis context to identify signals worth investigating. * Compare reports from different environments to find similar anomalies or assess whether CockroachDB contributes to an incident. Aegis gathers observations during check-ins, maintains cluster and workload context, and investigates anomalies. Through MCP, your agent uses the resulting reports and recommendations alongside its own tools and context. The MCP tools return Aegis's stored analysis and are separate from the tools Aegis uses to observe the cluster. Reports and recommendations live in the hosted Aegis service. Aegis needs its connection to the monitored cluster only to make new observations. When that connection is unavailable, your agent can still retrieve the stored reports over MCP. Check their observation times before using them to reason about a live incident. ## Connect through MCP Aegis exposes a hosted MCP endpoint: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} https://aegis.crdb.dev/mcp ``` Use an MCP client that supports remote HTTP servers and OAuth. Aegis supports dynamic client registration, PKCE, refresh tokens, and a consent screen. Authenticate with the CockroachDB Cloud account associated with your Aegis organization. To connect an agent: 1. Connect a cluster to Aegis and allow it to produce its initial reports. For instructions, see [How do I connect a cluster?](/docs/continuum/aegis-security-and-data-access#how-do-i-connect-a-cluster). 2. Add the Aegis endpoint to your agent's MCP client, as described for [Claude Code](#claude-code-setup) and [Codex CLI](#codex-cli-setup). 3. Complete the sign-in and consent flow. 4. Verify access with the read-only instance and report tools, as described in [Verify the MCP connection](#verify-the-mcp-connection). ### Claude Code setup Register the hosted server with your Claude Code client: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} claude mcp add --transport http aegis https://aegis.crdb.dev/mcp ``` Complete the client's OAuth sign-in and consent flow. If the new server's tools do not appear, restart the client. ### Codex CLI setup Register Aegis as a remote HTTP MCP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} codex mcp add aegis --url https://aegis.crdb.dev/mcp ``` If registration did not already start the OAuth sign-in flow, start it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} codex mcp login aegis ``` Sign in with the CockroachDB Cloud account associated with your Aegis organization and complete the consent flow. This sign-in is separate from the cluster's SQL credentials, which the MCP client never needs. ### Verify the MCP connection You can use the following read-only operations to check the connection: 1. Confirm that the client lists the six tools in [Available operations](#available-operations). If tools are missing, verify the remote HTTP URL, inspect the client's startup error, and reload or restart the client after configuration changes. 2. Ask the agent to call `list_instances` and select the intended instance by name. Use the returned Aegis instance `id` for subsequent calls. This is a different identifier from the CockroachDB Cloud cluster ID. 3. Call `get_instance` for that instance to inspect its status and check-in count, and confirm that it is the cluster you intended to monitor. 4. Call `get_reports` for the same instance to retrieve the cluster and workload reports from its latest completed check-in. Check the returned `check_in_id` and `as_of` timestamp. If the first check-in has not yet produced reports, confirm its progress in the Aegis web UI. 5. Call `list_recommendations` for that instance. A successful response can contain an empty list. To interpret that result alongside the reports, see [Why might there be no recommendations?](/docs/continuum/aegis-overview#why-might-there-be-no-recommendations). The `check_in_id` identifies the check-in represented by the response, and `as_of` identifies the report snapshot's timestamp. A check-in can carry reports forward unchanged, so these two fields tell you which check-in you are looking at, and each report's `changed`, `created_at`, and `version_id` fields tell you whether that check-in rewrote it. Read the observation times and metric windows inside each report to see what period it describes. The cluster and workload reports can have different update times. > [!NOTE] > > A report retrieved after a workload stops can still describe the running workload, even when the check-in completed after the stop. To confirm recovery, use a report whose observation window covers the period after the workload stopped. For example, try giving the agent this verification request: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Use Aegis MCP to find {workspace_name} with list_instances. Use its returned instance ID to call get_instance, get_reports, and list_recommendations. Report the check_in_id and as_of timestamp, each report's changed, created_at, and version_id fields, and the observation windows inside each report. If there are no recommendations, summarize the reports instead. This is a read-only check: leave recommendation state unchanged. ``` Replace `{workspace_name}` with the cluster's name in Aegis. Tool discovery shows which operations the client knows about, and a successful tool call confirms access to the selected instance. Aegis delivers reports and recommendations through tool calls, so an empty **Resources** or **Resource templates** list in your MCP client is expected. ### Available operations The hosted endpoint exposes the following operations: | Data | MCP tool | Operation | | - | - | - | | Instances | `list_instances` | List instances visible to the signed-in user. | | Instances | `get_instance` | Get an instance's metadata, status, and check-in count. | | Reports | `get_reports` | Get the latest or a specified check-in's cluster and workload reports. | | Recommendations | `list_recommendations` | List recommendations, optionally filtered by status: `open`, `snoozed`, `done`, `dismissed`, or `withdrawn`. | | Recommendations | `resolve_recommendation` | Mark an open recommendation done or dismissed, or reopen a recommendation that is done, dismissed, or snoozed. A dismissal accepts an optional reason code: `not_relevant`, `already_handled`, `not_actionable`, `bad_recommendation`, or `other`. | | Recommendations | `mark_recommendation_read` | Mark a recommendation read or unread. | Resolving a recommendation or marking it read updates Aegis's record of that recommendation. The monitored cluster is unchanged by this action, since you must separately apply any recommended changes through your normal change process. For more information about how Aegis controls access to cluster data, see [SQL permissions and data access](/docs/continuum/aegis-security-and-data-access#sql-permissions-and-data-access). ## Analyze a workload change through MCP This section describes a high-level workflow for comparing Aegis reports from before and after a workload change, to assess the change's effect on query performance and cluster health. The workflow is read-only and assumes a cluster that is already connected to Aegis. For detailed examples that follow this workflow with real workloads and measurements, see [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows). To compare reports around a workload change: 1. Select the intended instance with `list_instances` and retrieve the current reports with `get_reports`. Record the returned `check_in_id` as the baseline. Aegis stores every check-in's reports, so your agent does not need to keep the baseline in its own context; it can retrieve it again later by passing that `check_in_id` to `get_reports`. 2. Make the workload change through your normal operating process, and record its time and application name. The MCP report tools read analysis only; the workload runs separately. 3. Check progress with `get_instance`. After a later check-in completes, retrieve its reports with `get_reports`, and retrieve the baseline reports by passing the baseline `check_in_id`. Confirm that the new reports were updated and that their observations cover the change. If they do not yet cover it, wait for a later check-in and record the gap. 4. Compare workload characteristics, query latency, contention, and cluster resource observations. Distinguish Aegis's stated findings from conclusions your agent infers. When comparing with application measurements, account for differences in observation windows and in units, such as SQL statements per second versus transactions per second. 5. Retrieve recommendations with `list_recommendations` and review any proposed actions alongside the reports. If the list is empty, summarize the available analysis and its limitations. Apply changes through your normal review process. Set meaningful `application_name` values in your application's [SQL connection settings](/docs/stable/connection-parameters#additional-connection-parameters), such as `workload-loader` and `workload-runner`, so that Aegis can distinguish traffic sources in its workload observations. For example, after recording the baseline check-in and making the workload change, ask your agent to assess the evidence: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Use Aegis MCP to retrieve the status, reports, and recommendations for {workspace_name}. Compare the latest reports with the baseline reports from check-in {baseline_check_in_id} and with the workload change at {change_time_utc}. Report the check_in_id, as_of, each report's changed/created_at/version_id, and its observation windows. Explain changes in workload performance and cluster health, separating Aegis's findings from your inferences. If the reports do not yet cover the change, say so. If there are no recommendations, explain the relevant report findings instead. This is a read-only analysis: leave the cluster, the workload, and recommendation state unchanged. ``` Replace `{workspace_name}` with the cluster's name in Aegis, `{baseline_check_in_id}` with the check-in ID you recorded before the change, and `{change_time_utc}` with the workload change's UTC timestamp. To assess recovery after a workload stops, repeat the comparison with reports whose observations cover the period after it stopped. For a worked example, see [Step 6. Check recovery and choose a next action](/docs/continuum/aegis-example-workflows#step-6-check-recovery-and-choose-a-next-action) in the transaction contention workflow. ## See also * [Cockroach Aegis Overview](/docs/continuum/aegis-overview) * [Security and Administration](/docs/continuum/aegis-security-and-data-access) * [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows) # Investigate Workload Performance with Aegis Source: https://docs.cockroachlabs.com/docs/continuum/aegis-example-workflows > [!NOTE] > > **This feature is in [private preview](/docs/releases/cockroachdb-feature-availability)** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. The example workflows on this page show how to use Cockroach Aegis [reports and recommendations](/docs/continuum/aegis-overview#reports-and-recommendations) alongside your own measurements on a test cluster. In each workflow, you generate a workload, examine the evidence Aegis produces, decide whether a change is appropriate, and check the observations after the workload or configuration changes. This page describes two workflows: * [Understand transaction contention](#understand-transaction-contention): run a small TPC-C workload, read Aegis's analysis of hot-row contention, reduce concurrency, and compare the two phases. * [Review and apply an index recommendation](#review-and-apply-an-index-recommendation): create a table without a secondary index, generate a repeated full-scan query, review Aegis's index recommendation, apply the index, and verify the effect. Both workflows retrieve Aegis's analysis through MCP and apply any changes through a separate SQL connection. Aegis can also explain a workload's behavior without recommending a change, as the contention workflow shows. For information about how Aegis produces reports and recommendations, see [Cockroach Aegis Overview](/docs/continuum/aegis-overview). For MCP setup, see [Connect through MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). ## Before you begin * Use a dedicated, non-production cluster with no other workload. These examples write data and consume cluster resources. The reference contention run used a single-node, 4-vCPU Advanced cluster, which is sufficient for that example. A production configuration would add nodes for fault tolerance and load distribution. * [Connect the cluster to Aegis](/docs/continuum/aegis-security-and-data-access#connect-a-cluster). For a self-hosted cluster, keep the connector running throughout the tutorial. Cockroach Labs manages the connector for Cloud clusters. * Connect an MCP client and verify instance and report access. For instructions, see [Connect through MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). The instructions shown here rely heavily on your agent using MCP. * Install the `cockroach` binary and check `cockroach version`. Each example specifies its workload commands. For more information, see [`cockroach workload`](/docs/stable/cockroach-workload). * Use a separate SQL credential with permission to create the test database, read and write its tables, and create an index when an example requires it. Keep the Aegis connector role at its recommended read-only grants; the workload and any applied changes use this separate credential. * Set `PGURL` to this test cluster's connection URL, initially using `defaultdb`. Omit the password and retain `sslmode=verify-full` and the correct `sslrootcert` path. Supply the workload credential through `PGPASSWORD` using your normal secure credential-loading process, so that the password stays out of command arguments and shell history. For more information, see [Connection parameters](/docs/stable/connection-parameters). * For a CockroachDB Cloud cluster, use the `ccloud` CLI to obtain these values. `ccloud cluster sql --connection-url {cluster_name}` returns a connection URL that already includes `sslmode=verify-full` and the path to the downloaded CA certificate, and `ccloud cluster user create` creates the workload SQL user. For more information, see [Get connection information for a cluster](/docs/cockroachcloud/ccloud-reference#get-connection-information-for-a-cluster) and [Create a SQL user](/docs/cockroachcloud/ccloud-reference#create-a-sql-user). > [tab] Transaction contention > > ## Understand transaction contention > > In this example, you will run a small TPC-C workload and use Aegis reports to investigate [transaction contention](/docs/stable/performance-best-practices-overview#understanding-and-avoiding-transaction-contention). You will compare the reports with workload measurements, reduce concurrency, and check whether later observations cover the change. The goal is to understand the evidence Aegis provides, and to understand the workflow. > > Check [`cockroach workload run tpcc --help`](/docs/stable/cockroach-workload#tpcc-workload) before proceeding. Allow time for data initialization, two 12-minute measurement periods, and Aegis check-ins. The workload commands include a 30-second ramp before each measurement period. A check-in can complete without rewriting its reports, so allow for more than one check-in per phase. > > ### Step 1. Prepare the test dataset > > Confirm the SQL target and inspect the existing databases: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > cockroach sql --url "$PGURL" --execute 'SELECT now(), current_user; SHOW DATABASES;' > ``` > > Verify that the host in `PGURL` is the intended test cluster. Choose an unused database name, changing the following example if the name already exists, so that no existing database is overwritten: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > export AEGIS_TPCC_DB='aegis_tpcc_contention' > AEGIS_TPCC_ARTIFACTS=$(mktemp -d) > export AEGIS_TPCC_ARTIFACTS > > cockroach workload init tpcc \ > --db "$AEGIS_TPCC_DB" \ > --warehouses 10 --seed 1 --data-loader IMPORT \ > "$PGURL" > ``` > > Initialize the dataset once. Both phases use it, and their transactions will change its data. Wait for initialization to finish successfully before continuing. > > TPC-C includes payment and new-order transactions that update shared rows. With 10 warehouses, payments update a small set of warehouse totals, and district updates touch a small set of totals and order counters. Concurrent transactions can end up waiting on these rows even when overall CPU utilization is low. > > For the underlying concepts, read [Understand hotspots](/docs/stable/understand-hotspots), particularly [row hotspots](/docs/stable/understand-hotspots#row-hotspot), and [Understand and avoid transaction contention](/docs/stable/performance-best-practices-overview#understanding-and-avoiding-transaction-contention). > > ### Step 2. Capture an idle baseline > > After initialization finishes, select the intended Aegis instance over [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp) with `list_instances` and confirm its identity with `get_instance`. Retrieve `get_reports` and `list_recommendations` for that instance. > > Save the report bodies, `check_in_id`, and `as_of`, as well as each report's `changed`, `created_at`, and `version_id` fields. Read the observation times inside the reports. Your baseline should describe the idle cluster after initialization. If it still describes initialization or an earlier workload, retain that context and wait for observations of the idle cluster. > > Aegis checks in automatically. Wait for a scheduled check-in that covers the idle cluster. Retrieving reports through MCP leaves the check-in schedule unchanged. Check progress with `get_instance` before retrieving the completed snapshot. > > ### Step 3. Run the higher-concurrency phase > > Record the start time and run TPC-C with 32 active workers: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > date -u '+%Y-%m-%dT%H:%M:%SZ' > cockroach workload run tpcc \ > --db "$AEGIS_TPCC_DB" --warehouses 10 --seed 1 \ > --workers 32 --active-workers 32 --conns 32 \ > --wait 0 --max-rate 100 --max-ops 75000 \ > --duration 12m --ramp 30s --display-every 30s \ > --histograms "$AEGIS_TPCC_ARTIFACTS/32w.json" \ > --conn-vars application_name=aegis-docs-tpcc-32w,statement_timeout=30s \ > "$PGURL" > ``` > > The command disables TPC-C think time and caps workload operations at 100 per second. These operations are multi-statement transactions, so the rate differs from SQL statements per second, and the cap is an upper bound rather than a guaranteed throughput. > > > [!NOTE] > > > > This is a contention exercise rather than a compliant TPC-C benchmark or a capacity-sizing test. > > Watch the output, and stop the workload if it reports errors or the cluster shows unexpected resource pressure. Keep the load as specified; the goal is to see how Aegis gathers evidence, and getting a recommendation is optional. If your cluster can run this workload comfortably, you may not see a recommendation. Save the final totals and the end time after the command exits successfully. > > While the workload runs, wait for a scheduled check-in that covers the running workload. When it completes, retrieve and save the reports and recommendations through [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp), and confirm that the report bodies describe this application's activity during the run. > > ### Step 4. Interpret the contention evidence > > Ask your agent to compare the reports with the baseline using a prompt like the following: > > ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > Use Aegis MCP to retrieve get_instance, get_reports, and list_recommendations > for {instance_id}. Compare with the saved baseline and the TPC-C run that > started at {start_time_utc}, using application_name aegis-docs-tpcc-32w. > Report check_in_id and as_of, each report's changed/created_at/version_id, > and the observation windows in its body, and confirm that they cover this > phase. Explain any evidence of hot rows, lock waits, serialization retries, > and resource pressure. Separate Aegis's findings from your own inferences > and from the workload runner's measurements. If there are no > recommendations, explain the report findings instead. This is a read-only > analysis: leave the cluster, the workload, and recommendation state > unchanged. > ``` > > Replace `{instance_id}` with the Aegis instance ID and `{start_time_utc}` with the recorded UTC start time. Supply the saved baseline reports in the conversation. > > In the reference run, Aegis identified contention on `warehouse` and `district` rows, including warehouse payment totals and district order counters. Its cluster report showed CPU and disk headroom. The workload report identified serialization retries and explained why optimizer index suggestions were not promoted into recommendations: those suggestions targeted scan paths that were a small part of the cost in this synthetic workload. > > What follows are suggestions for interpreting the findings: > > * Contention on a small set of keys can occur at low overall CPU. Updates to a single [hot row](/docs/stable/understand-hotspots#row-hotspot) serialize on that row, so [adding nodes](/docs/stable/cockroach-start#add-a-node-to-a-cluster) or [an index](/docs/stable/indexes) can address different bottlenecks. > * Serialization retries are distinct from failed transactions. The reference workload may have reported zero terminal errors, while Aegis was likely to identify retry events. For more information, see [Transaction retry errors](/docs/stable/transaction-retry-error-reference). > * An empty recommendation list can accompany a report with substantial analysis. Read the report for the explanation. > * Verify the diagnosis with the cluster's contention and statement-performance views, filtered by the phase's application name and time window, following the instructions in [Monitor and analyze transaction contention](/docs/stable/monitor-and-analyze-transaction-contention). Note that cached contention entries can persist after load stops, so pair them with a time window when reading current contention. > > ### Step 5. Compare reduced concurrency > > Wait for the first command to exit. Record the next start time, then repeat the run with 8 active workers: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > date -u '+%Y-%m-%dT%H:%M:%SZ' > cockroach workload run tpcc \ > --db "$AEGIS_TPCC_DB" --warehouses 10 --seed 1 \ > --workers 32 --active-workers 8 --conns 32 \ > --wait 0 --max-rate 100 --max-ops 75000 \ > --duration 12m --ramp 30s --display-every 30s \ > --histograms "$AEGIS_TPCC_ARTIFACTS/8w.json" \ > --conn-vars application_name=aegis-docs-tpcc-8w,statement_timeout=30s \ > "$PGURL" > ``` > > Keep `--workers 32`, the warehouse count, and the connection-pool limit unchanged. `--active-workers 8` limits how many workers execute at once while preserving the existing workers' warehouse assignments. The pool closes idle connections, so the live connection count varies under lower load. Run the two phases sequentially on the same dataset. > > Repeat the check-in and report-retrieval process during this phase. Ask the agent to compare with the higher-concurrency reports, substituting the new application name and start time. Compare measured throughput as well as latency: lower concurrency can reduce contention while also reducing the rate of completed work. > > #### Reference measurements and limits > > A reference run we performed produced the following workload-client totals. Each phase had a 12-minute measurement period after a 30-second ramp: > > | Measurement | 32 active workers | 8 active workers | > | - | -: | -: | > | Completed transactions | 47,394 | 14,343 | > | Transactions/sec | 65.8 | 19.9 | > | Overall transaction p99 | 1,140.9 ms | 1,006.6 ms | > | New-order transaction p99 | 1,006.6 ms | 738.2 ms | > | Terminal workload errors | 0 | 0 | > > Separate SQL observations showed normalized CPU around 22–23% during the higher-concurrency phase and around 8% during the lower-concurrency phase. Warehouse-update profiles showed average statement service time around 42–44 ms at higher concurrency and 6–7 ms at lower concurrency. These are observations from selected statistics windows rather than whole-run aggregates or Aegis measurements. > > Throughput fell substantially while the overall client p99 improved modestly. The runs were sequential on a changing dataset, used a laptop client, and were an exercise rather than an isolated capacity benchmark. Statement service latency, sampled contention time, and client transaction latency have different meanings and measurement windows, so compare like with like. > > > [!WARNING] > > > > In this test, two completed check-ins during the lower-concurrency phase carried the earlier reports forward unchanged. Their `as_of` timestamps advanced, while both report bodies and `created_at` values still described the higher-concurrency phase. For this phase, the direct measurements above stand on their own, and Aegis's analysis of it was unavailable. > > If your reports are unchanged or do not cover the phase, record the gap. A new check-in ID indicates a new check-in, and each report's `changed` and `created_at` fields show whether its content is new. Wait for an applicable report, or use your existing monitoring tools for the comparison. > > ### Step 6. Check recovery and choose a next action > > After the second workload exits, record its end time and verify through your normal monitoring tools that workload traffic subsides. Keep the cluster connected to Aegis, allow time for idle observations, and retrieve reports after a later check-in. > > Confirm that the report contents cover the period after the stop time. In the reference test, direct SQL observations showed CPU returning to about 1.2%, while the first post-run MCP snapshot still carried the higher-concurrency reports. A later scheduled check-in produced reports describing an idle cluster with near-zero traffic and CPU around 1–3%, which confirmed recovery. > > Use what you learned to investigate a real workload's conflicting transactions and application requirements. Before choosing a mitigation, see [Reduce transaction contention](/docs/stable/performance-best-practices-overview#reduce-transaction-contention) and [Troubleshoot lock contention](/docs/stable/troubleshoot-lock-contention). > > Retain the test logs and reports needed for your comparison. Remove the test data and deprovision dedicated test resources through your normal cleanup process when you no longer need them. Note that stopping the TPC-C runs via [`cockroach workload`](/docs/stable/cockroach-workload) still leaves the database and the connector in place, and cloud cluster charges continue to accrue. > [tab] Index recommendation > > ## Review and apply an index recommendation > > In this example, you will create an orders table without a secondary index and run a query that counts a customer's pending orders. You use Aegis to identify the repeated full scan, review its recommendation, apply the index through a separate SQL connection, and compare the query plan and subsequent reports. > > This complements the [contention example](#understand-transaction-contention): an index lets a selective query skip unrelated rows, while a hot row remains contended regardless of indexing. Aegis recommendations depend on the observed workload and its context, so an [optimizer](/docs/stable/cost-based-optimizer) suggestion is an input to a recommendation. > > ### Step 1. Create a table without a secondary index > > Using the separate workload SQL credential, open `cockroach sql --url "$PGURL"`. Verify the intended test cluster and run `SHOW DATABASES`. The following example uses `aegis_index_example`; choose a different name throughout if that database already exists. > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE aegis_index_example; > CREATE TABLE aegis_index_example.public.orders ( > id INT8 PRIMARY KEY, > customer_email STRING NOT NULL, > product STRING NOT NULL, > amount DECIMAL(10,2) NOT NULL, > status STRING NOT NULL, > created_at TIMESTAMPTZ NOT NULL > ); > ``` > > Exit the SQL shell and seed 200,000 synthetic rows in eight batches of 25,000. Run this block in Bash. The subshell stops on the first error; if a batch fails, inspect the partial dataset before proceeding. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ( > set -e > for low in 1 25001 50001 75001 100001 125001 150001 175001; do > high=$((low + 24999)) > cockroach sql --url "$PGURL" --execute " > SET statement_timeout = '30s'; > INSERT INTO aegis_index_example.public.orders > SELECT i, > 'user' || (i % 1000)::STRING || '@example.com', > 'product-' || (i % 50)::STRING, > (i % 10000)::DECIMAL / 100, > CASE ((i // 1000) % 4) > WHEN 0 THEN 'pending' WHEN 1 THEN 'shipped' > WHEN 2 THEN 'delivered' ELSE 'returned' > END, > '2026-01-01'::TIMESTAMPTZ + i * INTERVAL '1 minute' > FROM generate_series($low, $high) AS g(i);" > done > ) > ``` > > Reconnect with `cockroach sql --url "$PGURL"`, collect table statistics, and verify the row count and indexes: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ANALYZE aegis_index_example.public.orders; > SELECT count(*) FROM aegis_index_example.public.orders; > SHOW INDEXES FROM aegis_index_example.public.orders; > ``` > > Continue only if the table has 200,000 rows and only the `orders_pkey` index. [`SHOW INDEXES`](/docs/stable/show-index) should return one row per column for that index. No index should yet exist that supports the `customer_email` and `status` filters. Remember to keep the Aegis connector role unchanged for this exercise. > > ### Step 2. Capture the query plan and Aegis baseline > > Run this read-only query with [`EXPLAIN ANALYZE`](/docs/stable/explain-analyze), which executes the query and reports its plan and measurements: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > EXPLAIN ANALYZE SELECT count(*) > FROM aegis_index_example.public.orders > WHERE customer_email = 'user42@example.com' > AND status = 'pending'; > ``` > > Save the output. Look for the index used, scan spans, rows decoded from KV, and execution time. In a reference run, the plan scanned all 200,000 rows of `orders_pkey` to find 50 matching orders. Three samples took 82–83 ms of execution time each. > > Through [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp), select the intended instance with `list_instances` and `get_instance`, then save `get_reports` and `list_recommendations`. Record report and recommendation IDs and timestamps. Existing reports might still describe an earlier workload; use their observation windows to establish the baseline. > > ### Step 3. Generate observations and retrieve the recommendation > > Exit the SQL shell. Run the following command in each of two terminals, with the same `PGURL` and securely loaded credential. Record the UTC start time. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > date -u '+%Y-%m-%dT%H:%M:%SZ' > cockroach sql --url "$PGURL" --watch 500ms --execute " > SET application_name = 'aegis-docs-index-before'; > SET statement_timeout = '30s'; > SELECT count(*) FROM aegis_index_example.public.orders > WHERE customer_email = 'user42@example.com' AND status = 'pending';" > ``` > > Each command repeatedly runs the same query and returns `50`. This is a small read workload rather than a throughput benchmark. Monitor cluster resources and client errors. [`--watch`](/docs/stable/cockroach-sql#repeat-a-sql-statement) runs until interrupted, so set a 20-minute timer, stay with the test, and stop both clients with **Ctrl+C** when you have the observations you need or the timer expires. Stop sooner if errors or unexpected resource pressure occur. > > Wait for a scheduled Aegis check-in while the workload is active. After it completes, retrieve `get_reports` and `list_recommendations`. Statistics collection and report updates can take time; leave cluster-wide collection intervals at their defaults. > > Compare each recommendation's `check_in_id` and timestamps with the report snapshot. In this test, the new recommendation became visible while its check-in was still running, before `get_reports` returned that check-in's completed reports. Report and recommendation reads are separate observations with their own timestamps. > > Ask your agent to review the evidence using a prompt like the following: > > ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > Use Aegis MCP to retrieve reports and recommendations for {instance_id}. > Find any recommendation about aegis_index_example.public.orders and the > aegis-docs-index-before workload that started at {start_time_utc}. > Report its identity, timestamps, proposed SQL, affected query, execution > count, rows scanned, latency, and the observation windows in the reports. > Explain why this index is useful and what storage and write costs it > introduces. Distinguish an optimizer suggestion from a recorded Aegis > recommendation. This is a read-only review: leave the cluster and > recommendation state unchanged. > ``` > > Replace `{instance_id}` and `{start_time_utc}` with your instance ID and recorded UTC start time. > > In a reference run, Aegis recorded a recommendation citing 603 executions, about 72.6 ms mean statement service latency, and 200,000 rows read per execution. It identified a missing [composite index](/docs/stable/indexes) and explained that the query would be covered without a `STORING` clause. It also noted the modest absolute workload and available cluster headroom. These were Aegis's reported statistics, which differ from the three individual `EXPLAIN ANALYZE` measurements above. > > If there is no applicable recommendation, inspect the reports, workload activity, permissions, and freshness. Aegis might judge the improvement low priority or retain older reports. Wait for a recommendation that targets this query; an optimizer suggestion alone is an input to Aegis's analysis, and this workflow reviews what Aegis recorded. > > ### Step 4. Review and apply the index > > Save the recommendation's ID, status, evidence, and proposed SQL, then stop both baseline clients. Confirm that the recommendation targets your test database and matches the query you measured. Check for an equivalent existing index and review the index's backfill and performance costs. For more information, see [Secondary index best practices](/docs/stable/schema-design-indexes#best-practices), [Index performance trade-offs](/docs/stable/indexes#performance), and [`CREATE INDEX`](/docs/stable/create-index). > > For the reference dataset, the reviewed recommendation was the following additive change: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE INDEX ON aegis_index_example.public.orders (customer_email, status); > ``` > > After review and approval, execute the applicable statement through the separate workload SQL connection. Wait for it to complete and check its result before proceeding. If the client command fails or times out, check whether the schema change started before retrying. For more information, see [Online schema changes](/docs/stable/online-schema-changes). > > Verify the index and result: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW INDEXES FROM aegis_index_example.public.orders; > SELECT count(*) > FROM aegis_index_example.public.orders > WHERE customer_email = 'user42@example.com' AND status = 'pending'; > ``` > > The reference run created `orders_customer_email_status_idx`, and the query still returned `50`. You applied the index through your own SQL connection. Resolving the recommendation through MCP would change only its Aegis state. > > ### Step 5. Verify the effect and revisit Aegis > > Repeat the exact `EXPLAIN ANALYZE` query from [Step 2](#step-2-capture-the-query-plan-and-aegis-baseline) without [forcing an index](/docs/stable/table-expressions#force-index-selection). Confirm that the optimizer selects the new index and scans a selective span rather than the whole table. > > The reference run produced these direct measurements on the same table: > > | Measurement | Before the index | After the index | > | - | - | - | > | Selected index | `orders_pkey` | `orders_customer_email_status_idx` | > | Rows decoded from KV | 200,000 | 50 | > | Bytes decoded from KV | 17 MiB | 3.1 KiB | > | Execution time, three samples | 82–83 ms | 0.70–0.73 ms | > | Query result | 50 | 50 | > > Repeat the two-client watch command with `application_name = 'aegis-docs-index-after'`, leaving the query, data, and 500-ms interval unchanged. Set a five-minute timer for this phase and stop both clients when it expires. Record start and end times, and wait for a scheduled check-in covering activity after the index became available. > > Retrieve [reports and recommendations](/docs/continuum/aegis-overview#reports-and-recommendations) again. Ask your agent to compare with the saved pre-change evidence, using the index-creation time and after-phase application name. Look for evidence that Aegis observed the schema change and the new query behavior. Check recommendation state separately, since Aegis updates its record during a later check-in. Fresh snapshot timestamps indicate a new check-in, and each report's fields and observation windows show whether it contains a new diagnosis. > > In the reference run, the next requested check-in updated both reports. Aegis identified the index-creation event and completed schema change, reported that the full-scan condition was gone, and noted a latest cluster p99 SQL service latency around 0.84 ms. That cluster percentile is a different measurement from the per-statement mean and individual query execution times above. > > See the [recommendation in the web UI](/docs/continuum/aegis-overview#find-reports-recommendations-and-activity). That reference-run screenshot uses the database name `aegis_index_20260909` instead of `aegis_index_example`. > > Retain the recommendation, query plans, report snapshots, and timing notes. Use your normal change process for any real application rollout. Remove the example database and deprovision dedicated test resources when you no longer need them; stopping the query clients leaves both in place. ## See also * [Cockroach Aegis Overview](/docs/continuum/aegis-overview) * [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem) * [Security and Administration](/docs/continuum/aegis-security-and-data-access) * [Understand hotspots](/docs/stable/understand-hotspots) * [Understand and avoid transaction contention](/docs/stable/performance-best-practices-overview#understanding-and-avoiding-transaction-contention) # Cockroach Aegis Overview Source: https://docs.cockroachlabs.com/docs/continuum/aegis-overview > [!NOTE] > > **This feature is in [private preview](/docs/releases/cockroachdb-feature-availability)** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. Cockroach Aegis is a managed service that monitors your CockroachDB clusters, investigates changes in cluster health and workload performance, and recommends actions for you to take based on what it finds. It is built on an **agent harness** designed specifically for monitoring and troubleshooting CockroachDB. Aegis supports both proactive tuning and reactive troubleshooting. It can identify opportunities to improve a workload before an incident, or investigate a change in latency, throughput, or cluster health when a problem occurs. It complements your existing monitoring tools with CockroachDB-specific analysis. Benefits of Aegis include: * Continuous, CockroachDB-aware monitoring that builds up context about your cluster over time. * Intelligent alerting and automatic investigations. When Aegis detects an anomaly or a potential issue, it can open an investigation and gather supporting evidence. * Recommendations that include supporting evidence and, where applicable, SQL for you to review and run. Recommendations are the primary information channel that you should pay attention to. * Periodic reports that explain what is happening on the cluster. * [Ask Aegis](#ask-aegis-cluster-aware-qa), a conversational user interface for questions about your cluster. * An [MCP endpoint](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp) that lets your own agents access Aegis's analysis. > [!NOTE] > > By default, Aegis's access to your cluster is read-only. It can only make recommendations about changes to make, which you can review and apply through your normal change process. This page describes: * How Aegis monitors your cluster through [check-ins](#automatic-monitoring-through-check-ins). * How [alerts and investigations](#intelligent-alerting-and-investigations) turn detected conditions into analysis. * How to read [reports and recommendations](#reports-and-recommendations). * How Aegis [uses accumulated context](#adaptive-learning), and how to steer it with custom instructions. * How to use the [Aegis web UI](#use-the-aegis-web-ui) and Ask Aegis. For information about connecting agents to Aegis, see [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem). For information about connecting a cluster, permissions, and data handling, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). ## Automatic monitoring through Check-ins Aegis reads cluster signals through a connection to your cluster, and records its analysis in a hosted service maintained by Cockroach Labs. A *check-in* is a periodic review of a cluster and its workload. During a check-in, Aegis compares current signals with its previous observations, refreshes its reports, and investigates conditions that warrant attention. Each check-in starts with Aegis reading the latest cluster and workload reports and any open investigation records, then using its tools to observe the cluster. What it records feeds the next check-in: * *Reports* carry updated cluster and workload context forward. * *Investigations* track deeper analysis of anomalies. * *Recommendations* surface actions for you to take. This cycle lets Aegis follow changes over time rather than analyzing each observation in isolation. Aegis checks in automatically and schedules its next check-in based on what it finds. You do not need to request routine check-ins. A healthy cluster is checked less frequently, and a condition that needs follow-up prompts an earlier check-in. An alert rule can also trigger a check-in ahead of schedule. For example, an alert rule that detects underreplicated ranges can wake Aegis to investigate the change, update the cluster report, and produce a recommendation if action is needed. To inspect check-in progress, open **Home** or the **check-ins** channel in the [web UI](#use-the-aegis-web-ui). Retrieving a report through MCP returns the latest completed analysis and leaves the check-in schedule unchanged. To stop scheduled check-ins temporarily, click **Pause** in the check-in controls on **Home** or in the **check-ins** channel. Click **Resume** to restart the schedule. You can still run a check-in manually while scheduled check-ins are paused. > [!NOTE] > > A check-in can carry an existing report forward unchanged. To find out whether a report reflects a recent change, check the observation times inside the report. When you retrieve reports through MCP, each report's `changed`, `created_at`, and `version_id` fields show whether that check-in rewrote it. For details, see [Verify the MCP connection](/docs/continuum/aegis-agentic-ecosystem#verify-the-mcp-connection). Interpret findings in the context of your cluster's topology and recent changes. For example, a single-node cluster cannot satisfy a [replication factor](/docs/stable/configure-replication-zones#num_replicas) of 3, so Aegis reports its ranges as [underreplicated](/docs/stable/cluster-setup-troubleshooting#replication-issues). That finding reflects a resilience limit of that configuration rather than a new failure. ## Intelligent Alerting and Investigations Aegis uses alert rules and investigations to turn detected conditions into analysis and possible next steps. * An *alert rule* defines a condition to evaluate against cluster metrics or SQL query results. * An *alert* records that a rule's condition was met, and can trigger a check-in. * An *investigation* records Aegis's analysis of a problem across check-ins, including the evidence it gathers and the hypotheses it evaluates. You can inspect investigations in the [web UI](#find-reports-recommendations-and-activity). During a scheduled or alert-triggered check-in, Aegis can open an investigation when a condition warrants further analysis. An alert does not necessarily result in an investigation. Aegis can also create alert rules to monitor conditions it identifies. An investigation tracks the analysis of a condition and has its own criteria for when it is complete. When the analysis identifies an action for you to take, Aegis records a recommendation. An investigation can also conclude without producing a recommendation. ## Reports and Recommendations Aegis produces two kinds of output: reports that describe the cluster and its workload, and recommendations that describe actions for you to take. ### Reports Aegis maintains two reports for each cluster: * The *cluster report* describes topology, configuration, resource utilization, and health. * The *workload report* describes the workloads running on the cluster and their performance characteristics, such as query throughput and latency. Aegis carries these reports between check-ins and updates them as conditions change. Read them in the web UI to understand the latest observed state, or provide them to your own agents through [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). For example, in a [controlled TPC-C test](/docs/continuum/aegis-example-workflows#understand-transaction-contention), the initial reports described an idle cluster. After the workload started, the updated workload report identified TPC-C traffic and attributed increased latency to contention on frequently updated `warehouse` and `district` rows, while the cluster report showed available CPU and disk capacity. Together, the reports distinguished workload contention from resource exhaustion. To reproduce this kind of comparison, see [Analyze a workload change through MCP](/docs/continuum/aegis-agentic-ecosystem#analyze-a-workload-change-through-mcp). ### Recommendations A recommendation contains an action, an explanation of why it matters, and the evidence behind it: the metrics, queries, or statistics Aegis observed, and links to relevant CockroachDB documentation. When the action can be expressed as SQL, the recommendation includes the statement for you to review. Examples include adding or dropping an index, changing a cluster setting, or investigating intermittent node restarts using information from outside the cluster. To act on a recommendation: 1. Review the proposed action and its supporting evidence. 2. Apply the change through your normal review and change process. 3. Compare subsequent reports and workload behavior with the evidence that prompted the change. 4. Mark the recommendation done or dismissed. To defer a recommendation, snooze it for one day or one week, optionally with a note. A snoozed recommendation returns to the active list when the snooze ends. You can reopen a recommendation that is done, dismissed, or snoozed. Aegis never applies its own recommendations. If new information changes the advice, Aegis records a replacement and marks the earlier recommendation **Revised**, preserving the history of the earlier advice. If a recommendation no longer applies, Aegis withdraws it. > [!TIP] > > A recommendation is the most important piece of information that Aegis surfaces to you. If you pay attention to nothing else Aegis does, you should read the recommendations. #### Why might there be no recommendations? A check-in can update the reports without identifying an action to recommend. An empty recommendation list means Aegis found nothing to recommend from what it observed. Read the reports for the observations and explanations behind that result, and for any limits on what Aegis could observe. For example, in the TPC-C test described in [Understand transaction contention](/docs/continuum/aegis-example-workflows#understand-transaction-contention), Aegis identified candidate indexes but did not recommend them. Its workload report explained that those indexes targeted queries contributing little to the workload's execution time and would not address the dominant row contention. The report explained the performance issue without proposing an index change. ## Adaptive Learning Aegis uses its history of observations, reports, investigations, and recommendations to keep its analysis specific to your cluster. For example, it detects a workload change by comparing current activity with an earlier report, and it remembers which recommendations it has already made. You can add your own context with **Custom Instructions**, which Aegis includes in every check-in. In the cluster workspace, go to **Custom instructions**, enter the context, and click **Save**. Use custom instructions to add business context that Aegis can't get from the cluster directly, such as a known issue, an intentional configuration choice, a planned migration, or an occasional analytics workload whose longer-running queries are expected. Adaptive learning means accumulating and using this cluster-specific context during analysis. Your cluster metadata and interactions with Aegis are not used to train or fine-tune AI models. For more information, see [How Aegis uses AI](/docs/continuum/aegis-security-and-data-access#how-aegis-uses-ai). ## Use the Aegis web UI The Aegis web UI provides a place to review the connected cluster's state, explore the evidence behind a recommendation, and ask questions through Ask Aegis. To give your own agents access to the same context using tools such as MCP, see [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem). ### Open a cluster workspace After you enroll and connect a cluster, sign in to Aegis with your CockroachDB Cloud account and open the cluster's workspace. The cluster name appears in the workspace header. For prerequisites, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). **Home** summarizes the latest reported cluster and workload state, open recommendations, and recent check-ins. ![Aegis Home showing the connected cluster's summary, recommendation history, recent check-ins, and workspace navigation.](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/aegis-home.png?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=461f88cd8a94e18af0e5442761724d8b) *Home brings together the connected cluster's latest summary, recommendations, and check-in history.* ### Find reports, recommendations, and activity Use the workspace navigation to find the information relevant to your task: | Destination | Use it to | | - | - | | **Home** | Review the current summary, recommendations, and recent check-ins. | | **Recommendations** | Read an action's supporting evidence, proposed SQL, status, and, for withdrawn recommendations, the reason the action no longer applies. Recommendations are grouped into **Active**, **Snoozed**, and **Settled**, and a revised recommendation appears beneath its replacement. | | **check-ins** | Review the history of check-ins. Use an entry's **Updated reports** and **Transcript** controls to inspect its reports and activity. | | **Alert rules** | Inspect the alert rules Aegis monitors and their current state. | | **Custom instructions** | Provide ongoing cluster context for check-ins, as described in [Adaptive Learning](#adaptive-learning). | ![Aegis Recommendations showing the Active and Settled groups, with the side panel open on an index recommendation that Aegis withdrew after the index was created, including its reason, finding, and supporting evidence.](https://mintcdn.com/cockroachlabs/gzSfgjbJch4uWhqZ/images/continuum/aegis-recommendations.png?fit=max\&auto=format\&n=gzSfgjbJch4uWhqZ\&q=85\&s=cb1aed2e7b495176da433a33ba59195e) *An index recommendation after the index was applied. Aegis retains the finding, evidence, and proposed SQL, marks the status `withdrawn`, and records the reason the action no longer applies.* When investigations are open, they appear in the **Investigations** section. For more information, see [Intelligent Alerting and Investigations](#intelligent-alerting-and-investigations). Check-ins run automatically. If you need an additional check-in, click **Check in** in the check-in controls on **Home** or in the **check-ins** channel. For worked examples of interpreting contention and acting on an index recommendation, see [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows). ### Ask Aegis: Cluster-aware Q\&A To open Ask Aegis, select **ask-aegis** in the workspace's **Channels** section. Ask a question about the cluster, or follow up on a report or recommendation. Ask Aegis has access to the same cluster context and tools that Aegis uses during check-ins, and it can consult the CockroachDB documentation to explain its answers. For example, ask: * How is this cluster looking overall right now? * What changed in this cluster's workload since the previous check-in? * What evidence supports this index recommendation? * What did the investigation find about the increase in latency? In the conversation shown below, the answer to the first question described an idle, healthy cluster, noted the single-node cluster's lack of fault tolerance, and cited the cluster and workload reports along with fresh metrics, node-liveness, and event-log observations. When you assess an answer, compare the report times with the observation window it states, since a report and a live observation can describe different periods. ![Ask Aegis answering a question about the connected cluster's current health, citing observations and noting the single-node cluster's lack of fault tolerance.](https://mintcdn.com/cockroachlabs/gzSfgjbJch4uWhqZ/images/continuum/aegis-ask-aegis.png?fit=max\&auto=format\&n=gzSfgjbJch4uWhqZ\&q=85\&s=d51d6037acb87689e17f47bcae34825d) *An Ask Aegis conversation about a cluster's health, including the answer's stated sources and observation window.* ## Demo video For a demonstration of how to use Cockroach Aegis, watch the following video: [YouTube video player](https://www.youtube.com/embed/L8y16x_B-Ig) ## See also * [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem) * [Security and Administration](/docs/continuum/aegis-security-and-data-access) * [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows) # Cockroach Aegis Security and Administration Source: https://docs.cockroachlabs.com/docs/continuum/aegis-security-and-data-access > [!NOTE] > > **This feature is in [private preview](/docs/releases/cockroachdb-feature-availability)** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. Cockroach Aegis helps you understand your cluster's health and workload while keeping you in control of data access and changes to your cluster. Aegis provides [recommendations](/docs/continuum/aegis-overview#recommendations) for you to review and apply. The following controls protect cluster access and operational data: * **Read-only cluster access.** Aegis runs under a dedicated SQL [user](/docs/stable/security-reference/authorization#users-and-roles) whose [privileges](/docs/stable/security-reference/authorization#privileges) determine what it can read. Aegis enforces read-only SQL access and cannot apply recommendations. * **Customer-specific data isolation.** Every customer instance is fully isolated. Your reports, cluster data, agent memory, and chat history are never visible to any other customer. * **Encryption and SSO support.** Connections to Aegis are authenticated and encrypted, and access is protected by single sign-on. This page answers questions about: * [Connecting a cluster](#connect-a-cluster), including the connector for self-hosted clusters. * [SQL permissions and data access](#sql-permissions-and-data-access). * [Authentication, SSO, and encryption](#authentication-sso-and-encryption). * [Data isolation, storage, retention, and deletion](#data-isolation-storage-retention-and-deletion). * [Auditing Aegis activity](#auditing-aegis-activity). * [How Aegis uses AI](#how-aegis-uses-ai). For an overview of what Aegis does, see [Cockroach Aegis Overview](/docs/continuum/aegis-overview). For information about connecting your own agents to Aegis, see [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem). ## Connect a cluster Aegis can monitor both CockroachDB Cloud and self-hosted clusters. The Aegis service itself is hosted by Cockroach Labs. * **CockroachDB Cloud clusters.** After your organization is enabled for the preview, connect your cluster to Aegis in the [CockroachDB Cloud Console](https://cockroachlabs.cloud/). This action creates the SQL user and IP allowlist entry required for cluster access. Cockroach Labs manages the connector. * **Self-hosted clusters.** You run a *connector* in your environment. The rest of this section applies to self-hosted clusters. ### Where does the connector run? The connector runs on a host in your environment that can reach your CockroachDB cluster. It connects to the cluster as a dedicated SQL user and opens an outbound, encrypted connection to the hosted Aegis service. The connector sends observed cluster metadata to Aegis. The cluster connection string and SQL credentials stay on the connector host. ### How do I connect a cluster? Sign in to [Aegis](https://aegis.crdb.dev/) with your CockroachDB Cloud account. When no cluster is connected yet, the workspace walks you through generating a connector token, installing the connector, creating the SQL user, and starting the connector. Connect a development, staging, or test cluster first. Before you begin, obtain the cluster's SQL connection URL, SQL CA certificate, and DB Console URL from its connection instructions or your administrator. The connector host must be able to reach both endpoints. You can start using Aegis without generating a workload. An initial report can describe an idle cluster, and completed check-ins can produce useful reports without recommendations. To interpret those results, see [Reports and Recommendations](/docs/continuum/aegis-overview#reports-and-recommendations). To connect an external agent, continue with [Connect through MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). ### Do I need inbound firewall access? Not from Aegis. The connector opens an outbound connection to the Aegis service, so neither the cluster nor the connector host needs to accept inbound connections from Aegis. The cluster does need to accept inbound connections from the connector host: the connector must reach the cluster's SQL and DB Console/metrics endpoints, so add the connector host to any cluster allowlist. Allow outbound traffic from the connector to `aegis.crdb.dev` on port `443`. A secure WebSocket connection carries requests from Aegis to the connector and results back to Aegis over that connector-initiated connection. Allow access to the cluster's [SQL port](/docs/stable/cockroach-start#networking) (typically `26257`) and [DB Console/metrics port](/docs/stable/cockroach-start#flags-http-addr) (typically `8080`), using the actual ports from the cluster's connection instructions. Check both paths, since a successful SQL connection only confirms the SQL path. If a connection times out, confirm that the cluster is ready, that the hostname and port are correct, and that the allowlist matches the connector host's actual outbound source IP. VPNs and proxies can route HTTPS and database traffic through different source IPs. Check both paths with your network administrator and use narrowly scoped allowlist entries. ### What if SQL connects but metrics fail? Before it connects to Aegis, the connector checks that it can reach the cluster's DB Console endpoint. If the DB Console is unreachable, the connector exits with an error. To start the connector while the DB Console is unreachable, for example while you correct an allowlist entry, pass `--skip-preflight`. The connector logs a warning and starts, but metric and node-status observations fail until the DB Console is reachable. Check the connector log for HTTP connection, certificate, or authentication errors. Without an override, the connector uses the SQL hostname on port `8080` for the DB Console/metrics endpoint. When the actual DB Console URL differs, start the connector with `--cockroach-http-addr` set to the cluster's HTTPS DB Console base URL. Use the cluster's public, verifiable DB Console URL when available. If its certificate is signed by a private or corporate CA that the connector does not trust, obtain that CA from your administrator and start the connector with `--cockroach-http-ca {http_ca_path}`, replacing `{http_ca_path}` with the absolute path to the trusted HTTP CA's PEM file. The SQL URL's `sslrootcert` configures SQL trust, and the HTTP endpoint can use a different CA. This setting changes certificate verification in the local connector only. The DB Console's certificate, its server configuration, and the operating system's trust store are unchanged. Keep certificate verification enabled rather than bypassing a certificate error with `--insecure`. If TLS succeeds but authentication fails, verify that the configured SQL user and password can sign in to the DB Console. ### What happens if the connector stops? Aegis stops collecting new observations from the cluster until the connector is running and connected again. Stored reports and recommendations remain available. To remove data, see [How do I delete my Aegis data?](#how-do-i-delete-my-aegis-data). Run the connector under a process supervisor so that it restarts after a process or host failure. The connector retries transient WebSocket disconnections automatically. A terminated process or a sleeping laptop needs the supervisor, or you, to bring the connector back. ## SQL permissions and data access ### What can Aegis read? With the recommended setup, Aegis reads system metadata and observability signals, including: * Cluster topology, configuration, and schema details such as table and index names. * Query performance statistics, including fingerprints, latency, and execution counts. * Index usage and workload-level index recommendations. * Resource metrics, cluster events, and status information. The dedicated SQL user's privileges determine what Aegis can read. With the [recommended grants](#which-sql-privileges-does-aegis-need), that excludes application tables, and queries against tables the user cannot read will fail. ### Which SQL privileges does Aegis need? For self-hosted clusters, the Aegis workspace's [setup flow](#how-do-i-connect-a-cluster) provides SQL to create a dedicated user with the following system privileges: | Privilege | Access | | - | - | | `VIEWACTIVITY` | View cluster activity statistics, including activity from other users. | | `VIEWCLUSTERSETTING` | View cluster settings and their values. | | `VIEWCLUSTERMETADATA` | View range, data distribution, store, and Raft information. | | `VIEWSYSTEMTABLE` | Read tables in the `system` database. | | `VIEWJOB` | View cluster jobs and schedules. | For details about these privileges, see [Authorization](/docs/stable/security-reference/authorization#supported-privileges). To inspect the system privileges granted to the SQL user created during setup, run: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SHOW SYSTEM GRANTS FOR {aegis_user}; ``` Replace `{aegis_user}` with the dedicated SQL user's name. ### Can Aegis change my cluster? No. Aegis's SQL access is read-only, and this is enforced in more than one place. Every statement is checked against a read-only allowlist before it runs, every SQL session is opened read-only, and every query runs inside an explicit read-only transaction. CockroachDB rejects any write attempted in that transaction, regardless of how it is spelled or which privileges the SQL user holds. Aegis records recommendations for you to review, and never applies them or changes your application's schema or data. You can review each recommendation and decide whether to apply changes through your normal change process. The [MCP recommendation-status operations](/docs/continuum/aegis-agentic-ecosystem#available-operations) change state in Aegis only. ### Can broader permissions expose more data? Yes. If you grant the SQL user access to application tables, query results from those tables can reach Aegis. Keep the role scoped to the recommended metadata privileges. ### What is the impact on my cluster? Aegis's tools run on a select set of stable interfaces, as a SQL user controlled by you. The privileges we recommend should not impact the cluster, but if they do, this user can also run at a lower quality of service (QoS) to reduce the impact on foreground traffic. Before deploying to production, evaluate the impact on a non-production cluster. ## Authentication, SSO, and encryption ### How do users sign in? Sign in with your [CockroachDB Cloud account](/docs/cockroachcloud/create-an-account). Your Aegis workspace is associated with your Cloud organization, including when the monitored cluster is self-hosted. ### Which credentials does each connection use? | Connection | Credential | Purpose | | - | - | - | | Browser or external MCP client to Aegis | CockroachDB Cloud sign-in; the MCP client manages its own OAuth credentials | Access the Aegis instances available to the signed-in user. | | Self-hosted connector to hosted Aegis | Connector token | Authenticate the connector to the Aegis service. | | Self-hosted connector to the cluster's SQL and DB Console endpoints | Dedicated SQL user's password | Read the cluster metadata allowed by that SQL user's grants. This is a SQL credential, distinct from your Cloud account password. | Each of these credentials authenticates one connection. Each MCP client signs in on its own. For MCP client setup, see [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). ### How are connections protected? Every connection to Aegis is authenticated and encrypted, whether from your browser, an MCP client, or a self-hosted connector. A self-hosted connector's SQL credentials remain in the environment where it runs and are never sent to Aegis. ## Data isolation, storage, retention, and deletion ### Is my data isolated from other customers? Yes. Reports, cluster context, agent memory, and chat history are visible only within your organization. Cluster memory is scoped to the cluster it describes and is never accessible to other customers. ### Where is my data stored? The Cockroach Labs-hosted Aegis service retains operational data, including reports, recommendations, agent memory, and chat history, while your instance is active. The hosted service is the store for these artifacts; the connector and monitored cluster hold none of them. This retained context lets separate check-ins build on earlier observations and lets you and your agents retrieve Aegis's analysis over time. ### How do I delete my Aegis data? Deleting an Aegis instance in the web UI deprovisions that instance and removes its associated operational data. ## Auditing Aegis activity ### How can I review what Aegis queried? Aegis connects through a dedicated SQL user, so you can identify its activity in cluster logs and statement statistics. The Aegis [web UI](/docs/continuum/aegis-overview#find-reports-recommendations-and-activity) also exposes check-in transcripts and tool-call records. ## How Aegis uses AI ### How does Aegis use AI? Aegis uses AI to analyze system metadata and workload signals to produce reports and recommendations. With the recommended privileges, it works from system metadata only, so it doesn't read your application data or row values, and you don't need to supply an AI model account or API key. Aegis only ever accesses what your SQL privileges allow, and the recommended setup keeps it scoped to metadata. See [SQL permissions and data access](#sql-permissions-and-data-access) for details. Your cluster metadata and interactions with Aegis are not used to train or fine-tune any AI model. ## See also * [Cockroach Aegis Overview](/docs/continuum/aegis-overview) * [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem) * [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows) # Authorization Source: https://docs.cockroachlabs.com/docs/continuum/authorization # Build AI Applications Overview Source: https://docs.cockroachlabs.com/docs/continuum/build-ai-applications-overview Cockroach Continuum Cloud stores and serves the data that AI applications and agents depend on. CockroachDB provides vector search for similarity workloads, and the MCP server gives agents and AI tools a structured way to work with your clusters. Continuum Cloud supports [cluster virtualization](/docs/continuum/virtualization-overview), allowing application developers and agents to deploy virtual clusters on a dedicated host cluster. Pages in this section: * [Vector Search](/docs/stable/vector) * [MCP Server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server) See also: * [Continuum virtualization](/docs/continuum/virtualization-overview) * [Build Your First Virtual Cluster](/docs/continuum/tutorial-virtual-cluster) # BYOC Architecture and Data Flow Source: https://docs.cockroachlabs.com/docs/continuum/byoc-architecture In a [Bring Your Own Cloud (BYOC)](/docs/continuum/byoc-overview) deployment, the CockroachDB cluster runs entirely inside your own cloud service provider account, and Cockroach Labs operates it remotely. This page describes a BYOC deployment's architecture, what crosses the boundary between your cloud provider account and Cockroach Labs, and what remains private within it. ## Control plane and data plane A BYOC deployment spans two environments, as shown in the following diagram: ![Architecture diagram showing the data and control planes within a BYOC deployment and what components are contained within](https://mintcdn.com/cockroachlabs/NDvB3yBjSImWcvVB/images/cockroachcloud/byoc-plane-architecture.png?fit=max\&auto=format\&n=NDvB3yBjSImWcvVB\&q=85\&s=fe7d4760dd27cd170f197c934b79ea18) * The *data plane* runs in your cloud provider account. The data plane contains everything that stores or serves your data: the CockroachDB nodes, their compute and encrypted storage, the managed Kubernetes cluster that supervises them, the load balancers and private endpoints your applications connect through, the networking configuration, and the storage bucket that holds your backups. * The *control plane* runs on Cockroach Labs infrastructure, hosted in the United States. The control plane provisions clusters, applies patches and version upgrades, orchestrates managed backups, monitors cluster health, drives automated healing, and serves the Cloud Console, the [Cloud API](/docs/continuum/cloud-api), and the [Terraform provider](/docs/continuum/terraform-provider). The control plane never becomes a dependency of your data path. Your applications connect to the cluster inside your own cloud provider account, and the cluster serves SQL traffic independently of any control plane infrastructure. ## How Cockroach Labs connects to your cloud provider account During setup you create a scoped cross-account identity and grant it to Cockroach Labs: an IAM role on Amazon Web Services (AWS), a service principal on Microsoft Azure, or a service account on Google Cloud Platform (GCP). The control plane assumes that identity and calls your cloud provider's own API endpoints to manage the resources that make up the cluster. These management API calls travel between Cockroach Labs and the cloud provider's control plane, not through your network. This design means every action Cockroach Labs takes is an authenticated cloud provider API call, and therefore appears in your own cloud provider audit log. A [Tailscale](https://tailscale.com/) router pod also runs in your Kubernetes cluster. Cockroach Labs engineers use it as a [jumpbox](https://en.wikipedia.org/wiki/Jump_server) for debugging, gated by per-session access controls. ## Application traffic Application traffic never transmits through the control plane infrastructure. Your application connects to a load balancer or private endpoint inside your own cloud provider account, which routes to the CockroachDB nodes in that account. Cockroach Labs is not involved in this traffic flow, and a Cockroach Labs outage does not interrupt it. ## What data leaves your cloud account ![Diagram showing data flows and operations within your cloud provider account and which data flows cross boundaries into the control plane](https://mintcdn.com/cockroachlabs/NDvB3yBjSImWcvVB/images/cockroachcloud/byoc-data-flows.png?fit=max\&auto=format\&n=NDvB3yBjSImWcvVB\&q=85\&s=5b8fb0208a7b0971b4df4aaac4ea5be6) The control plane needs some data from the data plane to operate the cluster, and health and diagnostic information to meet cluster SLAs. The following table lists the complete set of data categories that cross the boundary from your cloud provider account to Cockroach Labs: | Category | Contents | Contains customer data? | Location | | - | - | - | - | | Infrastructure and cluster metrics | Numeric time series describing node, storage, network, and cluster health; resource utilization; replication and range statistics | No | Cockroach Labs observability platform, United States | | Health and availability signals | Node liveness, pod status, cluster state | No | Cockroach Labs observability platform, United States | | Operational job telemetry | Status and outcome of provisioning, patching, upgrade, and backup jobs | No | Cockroach Labs observability platform, United States | | Redacted CockroachDB logs | [CockroachDB log events](/docs/stable/logging-overview) with sensitive values removed by [redaction](/docs/stable/configure-logs#redact-logs) | No. CockroachDB redacts values that could contain user data before the logs leave your cloud provider account. | Cockroach Labs observability platform, United States | | Organization and cluster configuration | Cluster name, region list, node counts, version, and the configuration you set in the Console or API | No | Cockroach Labs control plane, United States | For the detailed field list of what CockroachDB reports, refer to [Telemetry Collected by CockroachDB](/docs/stable/telemetry). The following data does **not** leave your cloud account: * Query results. * Unredacted log content. * Backups. CockroachDB writes managed backups to a bucket in your own cloud provider account and encrypts them with a key. You can control this key when using [customer-managed encryption keys (CMEK)](/docs/continuum/cmek). * Encryption keys. Data in transit between your cloud provider account and Cockroach Labs is encrypted. Traffic between CockroachDB nodes uses TLS 1.3, and client and application connections use TLS 1.2 or TLS 1.3. Connections cannot use TLS versions earlier than TLS 1.2. ## Logs BYOC uses two separate log streams. They differ in how they affect data residency and auditing. * **Redacted logs to Cockroach Labs**: CockroachDB [redacts](/docs/stable/configure-logs#redact-logs) [log events](/docs/stable/logging-overview), then sends them to the Cockroach Labs observability platform over an encrypted connection. Cockroach Labs site reliability engineers (SREs) and support engineers use this stream to operate, monitor, and troubleshoot your cluster. Cockroach Labs aggregates this stream in the United States regardless of which region your cluster runs in. You cannot disable this stream, because it is the mechanism by which Cockroach Labs operates the service. * **Unredacted logs to your own sink**: If you configure log export, CockroachDB writes full unredacted logs to a log sink inside your own cloud provider account: Amazon CloudWatch, Azure Monitor, or Google Cloud Logging. Cockroach Labs does not receive this stream. You control its retention, access, and downstream processing. Refer to [Export Logs From a CockroachDB Advanced Cluster](/docs/cockroachcloud/export-logs-advanced). To control what appears in log output, refer to [Redact logs](/docs/stable/configure-logs#redact-logs). ## Metrics The control plane collects cluster metrics to operate the service and to render the Console. You can additionally export metrics to a monitoring destination in your own cloud provider account. Refer to [Export Metrics](/docs/continuum/export-metrics). ## Telemetry You cannot disable operational telemetry for a BYOC cluster, in whole or in part. Telemetry is the mechanism by which Cockroach Labs provisions, patches, monitors, and supports your cluster, and by which Cockroach Labs delivers the availability commitment. Instead, you have the following controls over telemetry: * CockroachDB redacts log data before it leaves your cloud provider account. * For the list of collected fields, refer to [Telemetry Collected by CockroachDB](/docs/stable/telemetry). * You can export unredacted [logs](/docs/cockroachcloud/export-logs-advanced) and [metrics](/docs/continuum/export-metrics) to a destination in your own cloud provider account. The following Console features and support workflows also send data to Cockroach Labs: * **The Cloud Console SQL Shell**: The [SQL Shell](/docs/cockroachcloud/sql-shell) in the Cloud Console connects to your cluster through the control plane. When a user in your organization runs a statement there, the statement text and its results transit Cockroach Labs infrastructure. * **Console pages that display schema and query fingerprints**: The Console displays database, table, index, and column names, and the SQL Activity and Insights pages display normalized statement fingerprints, which omit literal values but retain object names. * **Authorized support investigation**: When you open a support case that requires live investigation, a Cockroach Labs engineer may need SQL-level access to diagnose the issue. This requires just-in-time elevation with a recorded justification, is time-bounded, and appears in your own cloud provider audit log. ## Availability during a control plane outage Because the control plane is not in the data path, a control plane outage affects only cluster management services, not database operations. The following are unaffected during a control plane outage: * All SQL traffic. Nodes continue serving reads and writes. * Raft consensus and replication, which run inside the CockroachDB process on the nodes themselves. * Execution of backup jobs that are already scheduled. * Recovery from a node failure. CockroachDB upreplicates data through Raft, and the in-account Kubernetes operator replaces the failed pod. This requires no control plane involvement. The following are unavailable during a control plane outage: * The Cloud Console. * The Cloud API and the Terraform provider. * Operations that change cluster size or configuration, such as scaling, upgrades, and new provisioning. The Cockroach Labs control plane has a recovery time objective (RTO) of 4 hours. Cockroach Labs publishes current and historical control plane status at [status.cockroachlabs.cloud](https://status.cockroachlabs.cloud/). ## Next steps * [Review the Continuum Cloud BYOC Overview](/docs/continuum/byoc-overview). * [Prepare a BYOC deployment in Amazon Web Services](/docs/continuum/byoc-aws-deployment). * [Prepare a BYOC deployment in Azure](/docs/continuum/byoc-azure-deployment). * [Prepare a BYOC deployment in Google Cloud Platform](/docs/continuum/byoc-gcp-deployment). # Prepare a Continuum Cloud BYOC Deployment in Amazon Web Services Source: https://docs.cockroachlabs.com/docs/continuum/byoc-aws-deployment This page describes how to prepare an Amazon Web Services (AWS) account to host a [BYOC deployment](/docs/continuum/byoc-overview) of a Continuum Cloud Mission Critical cluster. ## Prerequisites * Review the [shared responsibility model for BYOC](/docs/continuum/byoc-overview#shared-responsibility-model-for-byoc). Make sure you understand and acknowledge the responsibilities you hold for management of your cloud infrastructure and the necessary permissions you must grant to Cockroach Labs. * [Create a Continuum Cloud organization](/docs/continuum/create-a-continuum-organization) if you do not already have one. * BYOC is not enabled by default. To enable BYOC for your organization, contact your Cockroach Labs account team. * BYOC clusters use the [Mission Critical edition](/docs/continuum/editions-and-add-ons#editions) with provisioned storage. The Standard edition and usage-based storage are not available on BYOC. * Once you have prepared your cloud account for a BYOC deployment, cluster configuration and management is identical to a Mission Critical cluster in a Cockroach Labs account. Review [Create a Cluster](/docs/continuum/create-a-cluster) and the [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) documentation to plan your cluster sizing and resource allocation. * Review the cloud service regions supported by the Mission Critical edition in [Which cloud providers and regions does each edition support?](/docs/continuum/faq#which-cloud-providers-and-regions-does-each-edition-support) * Create an [API service account](/docs/cockroachcloud/managing-access#create-api-keys) to use the [Cloud API](/docs/continuum/cloud-api) with your Continuum Cloud organization. * More than one BYOC cluster can run in a single AWS account. If the account contains a BYOC cluster created before July 27, 2026, you must delete that cluster or migrate its data before you can create additional clusters in the account. * The AWS account must not contain resources that can affect the control plane's ability to operate on CockroachDB clusters. ## Step 1. Create a new AWS account Provision a new AWS account dedicated to CockroachDB infrastructure. BYOC requires you to grant Cockroach Labs permission to access and modify resources in this account. A dedicated account keeps these permissions separate from your other resources and allows Cockroach Labs to meet cluster uptime SLAs. You can reuse this account for multiple CockroachDB clusters. ## Step 2. Collect the Cockroach Labs IAM role ARN Cockroach Labs uses cross-account resource management to provision and manage resources in your AWS account. This requires two IAM roles: * An IAM role owned by Cockroach Labs which must be granted permissions to access an IAM role in your AWS account. * An intermediate IAM role in your AWS account which must be granted permissions to create and manage infrastructure. This IAM role is the target used by Cockroach Labs for cross-account management. In this step, use the [Cloud API](/docs/continuum/cloud-api) to get the **Amazon Resource Name (ARN)** of the IAM role that Cockroach Labs provisioned for your organization. Send a `GET` request to the `/v1/organization` endpoint of the [Cloud API](/docs/api/cloud/v1/organizations/get-information-about-the-callers-organization) similar to the following example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request GET \ --url https://cockroachlabs.cloud/api/v1/organization \ --header 'Authorization: Bearer {secret_key}' ``` Record the value of `cockroach_cloud_service_principals.aws.user_arn` in the response: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "cockroach_cloud_service_principals": { "aws": { "user_arn": "arn:aws:iam::{AWS Account ID}:example/arn" } } } ``` ## Step 3. Create the intermediate IAM role and apply permissions In this step, create the intermediate IAM role in your AWS account, then apply a trust relationship policy and permissions that allow Cockroach Labs to assume the intermediate role as needed. > [!CAUTION] > > This permission policy is the minimum required for Cockroach Labs to provision, operate, patch, back up, and heal your cluster over its full lifecycle. This is not a temporary permission set used only at time of creation. > > Do **not** remove, narrow, or add conditions to these permissions after setup, or use Resource Control Policies (RCPs) against this account that may affect control plane operations. Many of these permissions are used only during a specific lifecycle event, such as replacing a failed node, applying a patch, rotating an encryption key, or running a managed backup. Removing a permission might not cause an immediate error. A later operation that requires it, such as replacing a failed node or running a backup, can fail. Reducing the permission set voids the availability commitment for the cluster. > > Guardrails that restrict the account to particular regions or services, without touching the permissions the deployment requires, are compatible. Conditional or time-bounded policies, and service control policies that restrict this permission set, are not supported. Follow these steps to create the intermediate IAM role: 1. Open the AWS IAM console. 2. Create a new role. You can choose any name for this role. In these instructions the example role is named `CRLBYOCAdmin`. 3. Use the following trust relationship policy for the new role, using the ARN collected in the previous step: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::{AWS Account ID}:example/arn" }, "Action": "sts:AssumeRole" } ] } ``` 4. Apply the following IAM policy to the intermediate role: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "autoscaling:CreateAutoScalingGroup", "autoscaling:DeleteAutoScalingGroup", "autoscaling:Describe*", "autoscaling:Get*", "autoscaling:SetInstanceProtection", "autoscaling:TerminateInstanceInAutoScalingGroup", "autoscaling:UpdateAutoScalingGroup" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "ec2:AcceptVpcEndpointConnections", "ec2:AcceptVpcPeeringConnection", "ec2:AllocateAddress", "ec2:AssociateRouteTable", "ec2:AssociateVpcCidrBlock", "ec2:AttachInternetGateway", "ec2:AuthorizeSecurityGroupEgress", "ec2:AuthorizeSecurityGroupIngress", "ec2:CreateFlowLogs", "ec2:CreateInternetGateway", "ec2:CreateLaunchTemplate", "ec2:CreateLaunchTemplateVersion", "ec2:CreateNatGateway", "ec2:CreateRoute", "ec2:CreateRouteTable", "ec2:CreateSecurityGroup", "ec2:CreateSubnet", "ec2:CreateTags", "ec2:CreateVpc", "ec2:CreateVpcEndpoint", "ec2:CreateVpcEndpointServiceConfiguration", "ec2:CreateVpcPeeringConnection", "ec2:DeleteFlowLogs", "ec2:DeleteInternetGateway", "ec2:DeleteLaunchTemplate", "ec2:DeleteLaunchTemplateVersions", "ec2:DeleteNatGateway", "ec2:DeleteRoute", "ec2:DeleteRouteTable", "ec2:DeleteSecurityGroup", "ec2:DeleteSubnet", "ec2:DeleteVpc", "ec2:DeleteVpcEndpoints", "ec2:DeleteVpcEndpointServiceConfigurations", "ec2:DeleteVpcPeeringConnection", "ec2:Describe*", "ec2:DetachInternetGateway", "ec2:DisassociateAddress", "ec2:DisassociateRouteTable", "ec2:DisassociateVpcCidrBlock", "ec2:EnableEbsEncryptionByDefault", "ec2:Get*", "ec2:List*", "ec2:ModifySubnetAttribute", "ec2:ModifyVolume", "ec2:ModifyVpcAttribute", "ec2:ModifyVpcEndpointServiceConfiguration", "ec2:ModifyVpcEndpointServicePermissions", "ec2:RejectVpcEndpointConnections", "ec2:ReleaseAddress", "ec2:RevokeSecurityGroupEgress", "ec2:RevokeSecurityGroupIngress", "ec2:RunInstances", "ec2:StartVpcEndpointServicePrivateDnsVerification" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "eks:AssociateAccessPolicy", "eks:CreateAccessEntry", "eks:CreateCluster", "eks:DeleteAccessEntry", "eks:DeleteCluster", "eks:Describe*", "eks:DisassociateAccessPolicy", "eks:List*", "eks:UpdateAccessEntry", "eks:UpdateClusterConfig", "eks:UpdateClusterVersion" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "elasticloadbalancing:Describe*" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "iam:AddRoleToInstanceProfile", "iam:AttachRolePolicy", "iam:AttachUserPolicy", "iam:CreateAccessKey", "iam:CreateAccountAlias", "iam:CreateInstanceProfile", "iam:CreateOpenIDConnectProvider", "iam:CreatePolicy", "iam:CreateRole", "iam:CreateServiceLinkedRole", "iam:CreateUser", "iam:DeleteAccessKey", "iam:DeleteInstanceProfile", "iam:DeleteLoginProfile", "iam:DeleteOpenIDConnectProvider", "iam:DeletePolicy", "iam:DeletePolicyVersion", "iam:DeleteRole", "iam:DeleteRolePolicy", "iam:DeleteUser", "iam:DeleteUserPolicy", "iam:DetachRolePolicy", "iam:DetachUserPolicy", "iam:Get*", "iam:List*", "iam:PassRole", "iam:PutRolePolicy", "iam:PutUserPolicy", "iam:RemoveRoleFromInstanceProfile", "iam:TagPolicy" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "kafka:List*" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:Describe*", "logs:Get*", "logs:List*", "logs:PutRetentionPolicy", "logs:PutSubscriptionFilter" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:DeleteBucketPolicy", "s3:Describe*", "s3:Get*", "s3:List*", "s3:PutBucketTagging", "s3:PutEncryptionConfiguration", "s3:PutLifecycleConfiguration" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "servicequotas:GetServiceQuota" ], "Resource": "*" } ] } ``` ## Step 4. (Optional) Enable additional regions If you plan to use non-default AWS regions, you must manually enable them in the AWS Management Console. You must also activate [global STS tokens](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_region-endpoints.html) for these regions to work with CockroachDB. You may also need to adjust quotas for vCPU and EBS disk storage for the regions in which you plan to create your cluster. ## Step 5. Create the Continuum Cloud cluster In BYOC deployments, you can deploy CockroachDB clusters in the Cloud Console or with the [Cloud API](/docs/continuum/cloud-api). ### Create a cluster with the Cloud Console Follow these steps to create a Mission Critical cluster in the Cloud Console: 1. Open the Cloud Console and select the organization where BYOC is enabled. 2. Click **New cluster**. 3. For the edition, choose **Mission Critical**. BYOC is available only for the Mission Critical edition. 4. For the deployment, choose **Bring Your Own Cloud**, then select AWS as the cloud provider. 5. Under **Cloud account**, select the cloud account you prepared, or add a new cloud account. Enter the ARN associated with the intermediate IAM role that you created, *not* the ARN of the Cockroach Labs IAM role. 6. Configure the cluster's regions, capacity, and add-ons as desired, then create the cluster. Refer to [Create a Cluster](/docs/continuum/create-a-cluster) and [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) for more details. ### Create a cluster with the Cloud API Send a `POST` request to the `/v1/clusters` endpoint of the [Cloud API](/docs/continuum/cloud-api) to create a Mission Critical cluster, specifying the appropriate `edition`. The following example request creates a 3-node Mission Critical cluster in the `us-east-2` region, specifying the ARN associated with your intermediate IAM role: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request POST \ --url https://cockroachlabs.cloud/api/v1/clusters \ --header 'Authorization: Bearer {secret_key}' \ --json '{ "name": "byoc-aws-cluster-1", "provider": "AWS", "spec": { "dedicated": { "hardware": { "machine_spec": {"num_virtual_cpus": 4}, "storage_gib": 16 }, "region_nodes": {"us-east-2": 3} }, "edition": "MISSION_CRITICAL", "customer_cloud_account": { "aws": { "arn": "arn:aws:iam::{AWS Account ID}:example/arn" } } } }' ``` ## Create additional BYOC clusters An AWS account prepared for BYOC can support multiple Continuum Cloud clusters. To create an additional BYOC cluster in the same account, follow the [Create the Continuum Cloud cluster](#step-5-create-the-continuum-cloud-cluster) steps again. If you need to deploy the new cluster in non-AWS default regions, follow the [Enable additional regions](#step-4-optional-enable-additional-regions) step. ## Delete a BYOC cluster To delete a BYOC cluster, delete the cluster from the Cloud Console or with the [Cloud API](/docs/api/cloud/v1/clusters/delete-a-cluster-and-all-of-its-data). The Console steps are the same as for any Mission Critical cluster; refer to [Delete cluster](/docs/cockroachcloud/advanced-cluster-management#delete-cluster). Deleting the cluster is permanent and cannot be undone. When you delete a BYOC cluster, Cockroach Labs removes the managed resources that it provisioned in your AWS account for the cluster. The intermediate IAM role you created during setup is not removed automatically and remains under your control. You can remove it once deletion is complete. > [!CAUTION] > > Do not remove the intermediate IAM role or its permissions before deletion has finished. Cockroach Labs needs them to remove the managed resources from your AWS account. Removing access early can leave resources behind that you will need to clean up manually, and that will continue to incur charges from your cloud provider. ### Verify that deletion is complete After the cluster reports as deleted in the Cloud Console, verify that no managed resources remain in your AWS account. Review the AWS services covered by the permission set in Step 3 (for example, EC2, EKS, S3, and CloudWatch Logs) for resources associated with the cluster. If resources remain, contact your Cockroach Labs account team before removing them manually. ### Reuse the AWS account Before you reuse the AWS account for a subsequent BYOC deployment, verify that deletion of the previous cluster is complete and contact your Cockroach Labs account team to confirm that the account is ready for reuse. ## Next steps * [Connect to your cluster](/docs/continuum/connect-to-a-cluster) * [Manage your cluster using the Cloud API](/docs/continuum/cloud-api) * [Prepare your deployment for production](/docs/cockroachcloud/production-checklist) # Prepare a Continuum Cloud BYOC Deployment in Azure Source: https://docs.cockroachlabs.com/docs/continuum/byoc-azure-deployment This page describes how to prepare a Microsoft Azure account to host a [BYOC deployment](/docs/continuum/byoc-overview) of a Continuum Cloud Mission Critical cluster. ## Prerequisites * Review the [shared responsibility model for BYOC](/docs/continuum/byoc-overview#shared-responsibility-model-for-byoc). Make sure you understand and acknowledge the responsibilities you hold for management of your cloud infrastructure and the necessary permissions you must grant to Cockroach Labs. * [Create a Continuum Cloud organization](/docs/continuum/create-a-continuum-organization) if you do not already have one. * More than one BYOC cluster can run in a single Azure subscription. * BYOC is not enabled by default. To enable BYOC for your organization, contact your Cockroach Labs account team. * BYOC clusters use the [Mission Critical edition](/docs/continuum/editions-and-add-ons#editions) with provisioned storage. The Standard edition and usage-based storage are not available on BYOC. * Once you have prepared your cloud account for a BYOC deployment, cluster configuration and management is identical to a Mission Critical cluster in a Cockroach Labs account. Review [Create a Cluster](/docs/continuum/create-a-cluster) and the [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) documentation to plan your cluster sizing and resource allocation. > [!NOTE] > > BYOC on Azure supports a restricted set of VM series. Before sizing a deployment, confirm the supported VM series with your Cockroach Labs account team. * Review the cloud service regions supported by the Mission Critical edition in [Which cloud providers and regions does each edition support?](/docs/continuum/faq#which-cloud-providers-and-regions-does-each-edition-support) * The Azure subscription must not contain resources that can affect the control plane's ability to operate on CockroachDB clusters. * (Optional) Create an [API service account](/docs/cockroachcloud/managing-access#create-api-keys) to use the [Cloud API](/docs/continuum/cloud-api) with your Continuum Cloud organization. ## Step 1. Create a new Azure subscription Provision a new Azure subscription dedicated to CockroachDB infrastructure. BYOC requires you to grant Cockroach Labs permission to access and modify resources in this subscription. A dedicated subscription keeps these permissions separate from your other resources and allows Cockroach Labs to meet cluster uptime SLAs. You can reuse this subscription for multiple CockroachDB clusters. > [!CAUTION] > > After you create and configure this Azure subscription to host Continuum Cloud clusters, do not modify it. Changes to the subscription can cause unexpected problems with cluster operations. ## Step 2. Set up the admin App Registration After Cockroach Labs enables BYOC for your Continuum Cloud organization, Cockroach Labs creates an admin **App Registration** for your organization and gives you a URL for granting tenant-wide admin consent to it. Granting consent creates an admin **Service Principal** in your Microsoft Entra tenant. Cockroach Labs support uses this Service Principal to run the automation that sets up support infrastructure on the Kubernetes cluster. Visit this URL with a user account that is [authorized to consent on behalf of your organization](https://learn.microsoft.com/entra/identity/enterprise-apps/grant-admin-consent?pivots=portal#prerequisites). After you grant admin consent, grant the following roles to the admin Service Principal: * `Role Based Access Control Administrator` * `Azure Kubernetes Service Cluster User Role` * `Azure Kubernetes Service Contributor Role` * `Azure Kubernetes Service RBAC Cluster Admin` * `Managed Identity Contributor` * `Network Contributor` * `Storage Account Contributor` * `Storage Blob Data Contributor` * `Virtual Machine Contributor` * A custom role, `Resource Group Manager`, with the following permissions: * `Microsoft.Resources/subscriptions/resourceGroups/read` * `Microsoft.Resources/subscriptions/resourceGroups/write` * `Microsoft.Resources/subscriptions/resourceGroups/delete` * `Microsoft.Resources/subscriptions/resourceGroups/moveResources/action` * `Microsoft.Resources/subscriptions/resourceGroups/validateMoveResources/action` * `Microsoft.Resources/subscriptions/resourcegroups/deployments/read` * `Microsoft.Resources/subscriptions/resourcegroups/deployments/write` * `Microsoft.Resources/subscriptions/resourcegroups/resources/read` * `Microsoft.Resources/subscriptions/resourcegroups/deployments/operations/read` * `Microsoft.Resources/subscriptions/resourcegroups/deployments/operationstatuses/read` Cockroach Labs uses the custom `Resource Group Manager` role to create and manage resource groups in the subscription, instead of the broader `Contributor` role. ## Step 3. Set up the reader App Registration In addition to the admin application, Cockroach Labs provisions the **CockroachDB Cloud BYOC Reader** App Registration. Cockroach Labs support uses this App Registration for read access to Kubernetes infrastructure. This reader application also requires admin consent to deploy the reader Service Principal: 1. Log in to the Azure portal as a user with Global Administrator or Privileged Role Administrator permissions. 2. Open the following URL in your browser: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} https://login.microsoftonline.com/adminconsent?client_id=7f6538cb-f687-4411-9bbe-2f96bfbce028 ``` If your organization has multiple Microsoft Entra tenants, use the following URL instead, and replace `{customer-tenant-id}` with the ID of the tenant that contains your new Azure subscription: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} https://login.microsoftonline.com/{customer-tenant-id}/adminconsent?client_id=7f6538cb-f687-4411-9bbe-2f96bfbce028 ``` 3. Review the requested permissions and click **Accept**. 4. After you grant admin consent to the **CockroachDB Cloud BYOC Reader** App Registration, grant the following roles to the reader Service Principal: * `Reader` * `Azure Kubernetes Service Cluster User` * `Azure Kubernetes Service RBAC Reader` ## Step 4. Grant permissions to Entra groups with Azure Lighthouse Use [Azure Lighthouse](https://learn.microsoft.com/azure/lighthouse/overview) to give Cockroach Labs scoped, cross-tenant access to your subscription for support escalations. Access granted during an escalation is least-privilege and visible to you, and you can review and remove it at any time in the Azure portal. > [!CAUTION] > > The permission policy described in this step is the minimum required for Cockroach Labs to provision, operate, patch, back up, and heal your cluster over its full lifecycle. This is not a temporary permission set used only at time of creation. > > Do **not** remove, narrow, or add conditions to these permissions after setup. Many of these permissions are used only during a specific lifecycle event, such as replacing a failed node, applying a patch, rotating an encryption key, or running a managed backup. Removing a permission might not cause an immediate error. A later operation that requires it, such as replacing a failed node or running a backup, can fail. Reducing the permission set voids the availability commitment for the cluster. > > Guardrails that restrict the account to particular regions or services, without touching the permissions the deployment requires, are compatible. Azure policies that restrict this permission set are not supported. This Azure Lighthouse deployment grants permissions to Cockroach Labs' managed tenant, which has a tenant ID of `a4611215-941c-4f86-b53b-348514e57b45`, by assigning the following roles to the reader and admin Entra groups within the tenant: * Reader Entra group: * `Reader` * `Azure Kubernetes Service Cluster User Role` * Admin Entra group: * `Reader` * `Azure Kubernetes Service Contributor Role` * `Azure Kubernetes Service Cluster Admin` * `Managed Identity Contributor` * `Network Contributor` * `Storage Account Contributor` * `Virtual Machine Contributor` Follow these steps to enable secure, scoped access for Cockroach Labs to your subscription using Azure Lighthouse: 1. Save the following ARM template to a file named `byoc-lighthouse.json`: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "$schema": "https://schema.management.azure.com/schemas/2019-08-01/subscriptionDeploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "mspOfferName": { "type": "string", "metadata": { "description": "Specify a unique name for your offer" }, "defaultValue": "CockroachDB Cloud BYOC" }, "mspOfferDescription": { "type": "string", "metadata": { "description": "Name of the Managed Service Provider offering" }, "defaultValue": "Template for secure access to customer clusters in CockroachDB Cloud BYOC" } }, "variables": { "mspRegistrationName": "[guid(parameters('mspOfferName'))]", "mspAssignmentName": "[guid(parameters('mspOfferName'))]", "managedByTenantId": "a4611215-941c-4f86-b53b-348514e57b45", "authorizations": [ { "principalId": "c4139366-960c-431d-afad-29c65fd68087", "roleDefinitionId": "acdd72a7-3385-48ef-bd42-f606fba81ae7", "principalIdDisplayName": "CockroachDB Cloud BYOC Reader Entra Group" }, { "principalId": "c4139366-960c-431d-afad-29c65fd68087", "roleDefinitionId": "4abbcc35-e782-43d8-92c5-2d3f1bd2253f", "principalIdDisplayName": "CockroachDB Cloud BYOC Reader Entra Group" }, { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "acdd72a7-3385-48ef-bd42-f606fba81ae7", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group" } ], "eligibleAuthorizations": [ { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "ed7f3fbd-7b88-4dd4-9017-9adb7ce333f8", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group", "justInTimeAccessPolicy": { "multiFactorAuthProvider": "Azure", "maximumActivationDuration": "PT8H" } }, { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "0ab0b1a8-8aac-4efd-b8c2-3ee1fb270be8", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group", "justInTimeAccessPolicy": { "multiFactorAuthProvider": "Azure", "maximumActivationDuration": "PT8H" } }, { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "e40ec5ca-96e0-45a2-b4ff-59039f2c2b59", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group", "justInTimeAccessPolicy": { "multiFactorAuthProvider": "Azure", "maximumActivationDuration": "PT8H" } }, { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "4d97b98b-1d4f-4787-a291-c67834d212e7", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group", "justInTimeAccessPolicy": { "multiFactorAuthProvider": "Azure", "maximumActivationDuration": "PT8H" } }, { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "17d1049b-9a84-46fb-8f53-869881c3d3ab", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group", "justInTimeAccessPolicy": { "multiFactorAuthProvider": "Azure", "maximumActivationDuration": "PT8H" } }, { "principalId": "6532a4f2-3fa1-4b10-a4c2-05368c87c89a", "roleDefinitionId": "9980e02c-c2be-4d73-94e8-173b1dc7cf3c", "principalIdDisplayName": "CockroachDB Cloud BYOC Admin Entra Group", "justInTimeAccessPolicy": { "multiFactorAuthProvider": "Azure", "maximumActivationDuration": "PT8H" } } ] }, "resources": [ { "type": "Microsoft.ManagedServices/registrationDefinitions", "apiVersion": "2022-10-01", "name": "[variables('mspRegistrationName')]", "properties": { "registrationDefinitionName": "[parameters('mspOfferName')]", "description": "[parameters('mspOfferDescription')]", "managedByTenantId": "[variables('managedByTenantId')]", "authorizations": "[variables('authorizations')]", "eligibleAuthorizations": "[variables('eligibleAuthorizations')]" } }, { "type": "Microsoft.ManagedServices/registrationAssignments", "apiVersion": "2022-10-01", "name": "[variables('mspAssignmentName')]", "dependsOn": [ "[resourceId('Microsoft.ManagedServices/registrationDefinitions/', variables('mspRegistrationName'))]" ], "properties": { "registrationDefinitionId": "[resourceId('Microsoft.ManagedServices/registrationDefinitions/', variables('mspRegistrationName'))]" } } ], "outputs": { "mspOfferName": { "type": "string", "value": "[concat('Managed by', ' ', parameters('mspOfferName'))]" }, "authorizations": { "type": "array", "value": "[variables('authorizations')]" }, "eligibleAuthorizations": { "type": "array", "value": "[variables('eligibleAuthorizations')]" } } } ``` 2. Deploy the template at the subscription scope using [Azure CLI, Azure PowerShell, or Azure Portal](https://learn.microsoft.com/azure/lighthouse/how-to/onboard-customer?tabs=azure-portal#deploy-the-azure-resource-manager-template). The following example command uses the Azure CLI: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} az deployment sub create \ --name cockroach-byoc-lighthouse \ --location {region} \ --template-file byoc-lighthouse.json ``` ## Step 5. Register resource providers Register the following [resource providers](https://learn.microsoft.com/azure/azure-resource-manager/management/resource-providers-and-types) in the Azure subscription: * `Microsoft.ContainerService` * `Microsoft.ManagedIdentity` * `Microsoft.Network` * `Microsoft.Quota` * `Microsoft.Storage` ## Step 6. Create the Continuum Cloud cluster In BYOC deployments, you can deploy CockroachDB clusters in the Cloud Console or with the [Cloud API](/docs/continuum/cloud-api). ### Create a cluster with the Cloud Console Follow these steps to create a Mission Critical cluster in the Cloud Console: 1. Open the Cloud Console and select the organization where BYOC is enabled. 2. Click **New cluster**. 3. For the edition, choose **Mission Critical**. BYOC is available only for the Mission Critical edition. 4. For the deployment, choose **Bring Your Own Cloud**, then select Azure as the cloud provider. 5. Under **Cloud account**, select the cloud account you prepared, or add a new cloud account. Enter the tenant ID and subscription ID associated with your Azure subscription. 6. Configure the cluster's regions, capacity, and add-ons as desired, then create the cluster. Refer to [Create a Cluster](/docs/continuum/create-a-cluster) and [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) for more details. ### Create a cluster with the Cloud API Send a `POST` request to the `/v1/clusters` endpoint of the [Cloud API](/docs/continuum/cloud-api) to create a Mission Critical cluster, specifying the appropriate `edition`. The following example request creates a 3-node Mission Critical cluster in the `centralus` region, specifying the `subscription-id` and `customer-tenant-id` associated with your Azure subscription: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request POST \ --url https://cockroachlabs.cloud/api/v1/clusters \ --header "Authorization: Bearer {secret_key}" \ --json '{ "name":"byoc-azure-cluster-1", "provider": "AZURE", "spec": { "edition": "MISSION_CRITICAL", "customer_cloud_account": { "azure": { "subscription_id": "{subscription-id}", "tenant_id": "{customer-tenant-id}" } }, "dedicated": { "hardware": { "machine_spec": { "num_virtual_cpus": 4 }, "storage_gib": 16 }, "region_nodes": { "centralus": 3 } } } }' ``` ## Create additional BYOC clusters An Azure subscription prepared for BYOC can support multiple Continuum Cloud clusters. To create an additional BYOC cluster in the same subscription, follow the [Create the Continuum Cloud cluster](#step-6-create-the-continuum-cloud-cluster) steps again. ## Delete a BYOC cluster To delete a BYOC cluster, delete the cluster from the Cloud Console or with the [Cloud API](/docs/api/cloud/v1/clusters/delete-a-cluster-and-all-of-its-data). The Console steps are the same as for any Mission Critical cluster; refer to [Delete cluster](/docs/cockroachcloud/advanced-cluster-management#delete-cluster). Deleting the cluster is permanent and cannot be undone. When you delete a BYOC cluster, Cockroach Labs removes the managed resources that it provisioned in your Azure subscription for the cluster. The admin and reader Service Principals created when you granted admin consent during setup and the Azure Lighthouse registration you deployed are not removed automatically and remain under your control. You can remove them once deletion is complete. > [!CAUTION] > > Do not remove the Service Principals, the Azure Lighthouse registration, or their role assignments before deletion has finished. Cockroach Labs needs them to remove the managed resources from your Azure subscription. Removing access early can leave resources behind that you will need to clean up manually, and that will continue to incur charges from your cloud provider. ### Verify that deletion is complete After the cluster reports as deleted in the Cloud Console, verify that no managed resources remain in your Azure subscription. Review the resource groups in the subscription for resources associated with the cluster. If resources remain, contact your Cockroach Labs account team before removing them manually. ### Reuse the Azure subscription Before you reuse the Azure subscription for a subsequent BYOC deployment, verify that deletion of the previous cluster is complete and contact your Cockroach Labs account team to confirm that the subscription is ready for reuse. ## Next steps * [Connect to your cluster](/docs/continuum/connect-to-a-cluster) * [Manage your cluster using the Cloud API](/docs/continuum/cloud-api) * [Prepare your deployment for production](/docs/cockroachcloud/production-checklist) # Continuum Cloud BYOC FAQ Source: https://docs.cockroachlabs.com/docs/continuum/byoc-faq This page answers frequently asked questions about [Bring Your Own Cloud (BYOC)](/docs/continuum/byoc-overview) deployments in Cockroach Continuum Cloud. For more detail, refer to the pages linked in each answer. ## Architecture and data ### What runs in my cloud account, and what runs at Cockroach Labs? The CockroachDB nodes, their storage, the managed Kubernetes layer, the load balancers, the networking, and the backup bucket all run in your cloud account. Cockroach Labs runs the control plane, which provisions, patches, backs up, and monitors the cluster. Refer to [Continuum Cloud BYOC Overview](/docs/continuum/byoc-overview). ### Does my application traffic go through Cockroach Labs? No. Your application connects to a load balancer or private endpoint inside your own cloud account and reaches the nodes directly. ### What data leaves my cloud account? Infrastructure and cluster metrics, health signals, operational job telemetry, and CockroachDB logs that are redacted before they leave. ### Does Cockroach Labs see my data? Not through telemetry, metrics, or the redacted log stream. Query text can reach Cockroach Labs in two circumstances, both of which you control: * When a [user in your organization](/docs/cockroachcloud/managing-access#manage-an-organizations-users) runs a statement in the [SQL Shell](/docs/cockroachcloud/sql-shell) in the Cloud Console, which the control plane proxies. * When you authorize a support engineer to conduct a live investigation, which requires just-in-time elevation, is time-bounded, and is recorded in your own cloud provider audit log. Database, table, and column names are also visible in the Console. ### Where do my logs go? Two places. Redacted logs go to Cockroach Labs, in the United States, and are used to operate and support your cluster. Unredacted logs go only to a sink in your own cloud account, and only if you configure log export. ### Where is the control plane hosted? In the United States. ### Is my data encrypted at rest, and can I use my own keys? Yes to both. Cluster storage is encrypted at the infrastructure level using your cloud provider's disk encryption, independently of any configuration you apply. You can additionally enable customer-managed encryption keys (CMEK), supported with AWS KMS, Google Cloud KMS, and Azure Key Vault, covering both cluster-level encryption and managed backups. Key material stays in your own cloud account. Refer to [Customer-Managed Encryption Keys (CMEK)](/docs/continuum/cmek). ### Is data encrypted in transit between my account and Cockroach Labs? Yes. Node-to-node traffic uses TLS 1.3, and client connections use TLS 1.2 or TLS 1.3. ## Security and access ### Is there a VPN or agent connecting Cockroach Labs to my network? Yes. A Tailscale router pod runs in your Kubernetes cluster. Cockroach Labs engineers use it as a jumpbox for debugging, gated by per-session access controls. ### Can I view every action Cockroach Labs takes in my account? Yes, in your own cloud provider audit log: CloudTrail on AWS, the Activity Log on Azure, and Cloud Audit Logs on Google Cloud Platform. ### Do Cockroach Labs engineers have standing access to my account? No. Access is just-in-time, requires a recorded justification, expires, and is authenticated through the Cockroach Labs identity provider with multi-factor authentication. ### How quickly is a departing Cockroach Labs engineer's access removed? There is no persistent grant to remove. The engineer's identity provider account is deactivated within one business day of termination, and they held no standing entitlement to your cloud account before that. ### Can I revoke Cockroach Labs access? Yes, immediately and unilaterally. Cluster management, patching, backups, and the availability commitment stop. SQL traffic continues. ### Can I reduce the permissions, or apply conditional or time-based policies? No. The published set is the minimum required across the cluster lifecycle. Reducing it typically fails weeks later, during a patch, node replacement, or backup, rather than at the moment of the change. ### Can I use different permissions for production and non-production? Not within a single policy. To separate production and non-production environments by identity and blast radius, deploy them into separate cloud accounts, each with its own cross-account identity. Because multiple BYOC clusters can share one cloud account, this separation is a deployment choice that you must make deliberately. ## Compliance ### What is the compliance status of BYOC specifically? A SOC 2 Type I report and a SOC 2 Type II readiness letter are available under a non-disclosure agreement (NDA). Delivery of the SOC 2 Type II report is targeted for December 18, 2026. BYOC is also covered by ISO/IEC 27001:2022 certification, PCI DSS Level 1 Service Provider validation, and an annual third-party penetration test. ### How do I obtain the reports? Through your Cockroach Labs account team, under an NDA. ### Does BYOC meet EEA data residency requirements? Row-level data stays in your own cloud account, in the region you select, and Cockroach Labs does not process it. Cockroach Labs processes redacted operational telemetry and log data, which contain no personal or payment data, in the United States. ## Availability ### What happens if the Cockroach Labs control plane goes down? Your database keeps serving traffic. [Raft](/docs/stable/architecture/replication-layer#raft) replication, [range](/docs/stable/architecture/overview#architecture-range) healing, and already-scheduled [managed backups](/docs/continuum/managed-backups) continue, and a failed node is still replaced automatically. The Console, [Cloud API](/docs/continuum/cloud-api), and Terraform provider become unavailable, as do operations that change the cluster's shape. The control plane recovery time objective is 4 hours. ### What voids the availability commitment? Removing or restricting the cross-account identity or its permissions, exhausting required service quotas, or modifying managed resources in the account outside of Cockroach Labs. ## Editions and billing ### Which edition and storage model does BYOC use? BYOC clusters use the [Mission Critical edition](/docs/continuum/editions-and-add-ons#editions) with provisioned storage. The Standard edition and [usage-based storage](/docs/continuum/plenum-overview) are not available on BYOC. ### Can I mix BYOC and fully managed clusters in one organization? Yes. A Continuum Cloud organization can run BYOC clusters and clusters in Cockroach Labs accounts side by side. Each cluster is billed at its applicable rate, and credits are shared across the organization. An organization can also be restricted so that only BYOC clusters can be created in it. ### How is a BYOC cluster billed? Cockroach Labs meters the vCPUs the cluster consumes and charges for them at the BYOC rate, drawn from your organization's credits. For rates, contact your Cockroach Labs account team. The cloud resources themselves are provisioned in your own cloud account and billed directly by your cloud provider, including any discounts or commitments you have in place. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons#billing-and-metering). ### Can I run virtual clusters on a BYOC cluster? Yes, in [preview](/docs/continuum/feature-availability) on AWS and GCP. Cluster virtualization on BYOC is enabled on request through your Cockroach Labs account team. Because the feature is in preview, host clusters and virtual clusters are not covered by the availability SLA. Refer to [Work with Virtual Clusters](/docs/continuum/virtual-clusters). ## Limitations and operations ### Can I run more than one cluster in a single cloud account? Yes. Multiple BYOC clusters can share a single cloud account. On AWS, the account must not contain a BYOC cluster created before July 27, 2026. If it does, you must delete that cluster or migrate its data first. The account must still be dedicated to CockroachDB infrastructure and free of other workloads at the time of setup. ### Does BYOC support VPC or VNet peering? BYOC supports VPC peering only on GCP, as with other Continuum Cloud clusters. On AWS and Azure, applications connect privately only through your cloud provider's private endpoint service. Refer to [Network Authorization for CockroachDB Cloud](/docs/cockroachcloud/network-authorization). ### Which regions and machine types can I use? BYOC region availability follows the Mission Critical edition. Refer to [Which cloud providers and regions does each edition support?](/docs/continuum/faq#which-cloud-providers-and-regions-does-each-edition-support) Machine type availability varies by cloud provider. Refer to the deployment guide for your cloud provider. ### Who collects diagnostic bundles on a BYOC cluster? Cockroach Labs support collects [diagnostics](/docs/stable/cockroach-debug-zip) on a BYOC cluster as part of the managed service. ### Do I need to open support tickets with my cloud provider? Occasionally, yes. Because the account is yours, you must raise some issues with your cloud provider, such as service quota increases or capacity availability in a region. ### Why does my cloud bill include NAT gateway charges? Mission Critical clusters run on private nodes, because the Mission Critical edition does not allow public network visibility. Outbound traffic from the nodes, such as operational telemetry, writes to your backup bucket, and changefeed traffic to external sinks, leaves your cloud account through a NAT gateway, which your cloud provider bills per hour and per gigabyte processed. ### How do I delete a BYOC deployment? Use the Cloud Console or the [Cloud API](/docs/continuum/cloud-api). Some resources, including your backups and the identity you granted, remain in your cloud account after deletion. Refer to the deployment guide for your cloud provider. ## Next steps * [Continuum Cloud BYOC Overview](/docs/continuum/byoc-overview) * [Prepare a Continuum Cloud BYOC Deployment in Amazon Web Services](/docs/continuum/byoc-aws-deployment) * [Prepare a Continuum Cloud BYOC Deployment in Azure](/docs/continuum/byoc-azure-deployment) * [Prepare a Continuum Cloud BYOC Deployment in Google Cloud Platform](/docs/continuum/byoc-gcp-deployment) # Prepare a Continuum Cloud BYOC Deployment in Google Cloud Platform Source: https://docs.cockroachlabs.com/docs/continuum/byoc-gcp-deployment This page describes how to prepare a Google Cloud Platform (GCP) account to host a [BYOC deployment](/docs/continuum/byoc-overview) of a Continuum Cloud Mission Critical cluster. ## Prerequisites * Review the [shared responsibility model for BYOC](/docs/continuum/byoc-overview#shared-responsibility-model-for-byoc). Make sure you understand and acknowledge the responsibilities you hold for management of your cloud infrastructure and the necessary permissions you must grant to Cockroach Labs. * [Create a Continuum Cloud organization](/docs/continuum/create-a-continuum-organization) if you do not already have one. * More than one BYOC cluster can run in a single GCP project. If the project contains a BYOC cluster created before multiple-cluster support was enabled, you must delete that cluster or migrate its data before you can create additional clusters in the project. * BYOC is not enabled by default. To enable BYOC for your organization, contact your Cockroach Labs account team. * BYOC clusters use the [Mission Critical edition](/docs/continuum/editions-and-add-ons#editions) with provisioned storage. The Standard edition and usage-based storage are not available on BYOC. * Once you have prepared your cloud account for a BYOC deployment, cluster configuration and management is identical to a Mission Critical cluster in a Cockroach Labs account. Review [Create a Cluster](/docs/continuum/create-a-cluster) and the [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) documentation to plan your cluster sizing and resource allocation. * Review the cloud service regions supported by the Mission Critical edition in [Which cloud providers and regions does each edition support?](/docs/continuum/faq#which-cloud-providers-and-regions-does-each-edition-support) * The GCP project must not contain resources that can affect the control plane's ability to operate on CockroachDB clusters. * Create an [API service account](/docs/cockroachcloud/managing-access#create-api-keys) to use the [Cloud API](/docs/continuum/cloud-api) with your Continuum Cloud organization. ## Step 1. Create a new GCP project Provision a new GCP project dedicated to CockroachDB infrastructure. BYOC requires you to grant Cockroach Labs permission to access and modify resources in this project. A dedicated project keeps these permissions separate from your other resources and allows Cockroach Labs to meet cluster uptime SLAs. You can reuse this project for multiple CockroachDB clusters. The following requirements apply to the GCP project used for your BYOC deployment: * The project ID **must not** begin with the reserved prefix `crl-`. * [Enable](https://docs.cloud.google.com/endpoints/docs/openapi/enable-api) the Service Usage API and the Cloud Resource Manager APIs for this project. Cockroach Labs enables additional APIs as needed, but you must enable these two first. ## Step 2. Grant permissions to the Cockroach Labs service account Cockroach Labs uses cross-account service account impersonation to provision and manage resources in your GCP project. This requires two GCP service accounts: * A service account owned by Cockroach Labs which must be granted roles to view and access service accounts in your GCP project. * An intermediate service account in your GCP project which must be granted roles to create and manage infrastructure. This service account is the target used by Cockroach Labs for cross-account impersonation, and you specify this service account when creating Continuum Cloud clusters in this organization. In this step, use the [Cloud API](/docs/continuum/cloud-api) to collect the email address of the Cockroach Labs service account and grant it the necessary roles. Follow these steps to identify the Cockroach Labs service account and grant it the necessary roles: 1. Send a `GET` request to the `/v1/organization` endpoint of the [Cloud API](/docs/api/cloud/v1/organizations/get-information-about-the-callers-organization) similar to the following example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request GET \ --url https://cockroachlabs.cloud/api/v1/organization \ --header 'Authorization: Bearer {secret_key}' ``` In the response, the value of `cockroach_cloud_service_principals.gcp.service_account_email` is the email address of the Cockroach Labs service account: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "cockroach_cloud_service_principals": { "gcp": { "service_account_email": "{Cockroach Labs service account}" } } } ``` 2. Grant this Cockroach Labs service account the following roles in the GCP IAM Console: * `Service Account Token Creator (roles/iam.serviceAccountTokenCreator)` * `View Service Accounts (roles/iam.serviceAccountViewer)` ## Step 3. Configure the intermediate service account In this step, create the intermediate service account in your GCP project and grant it the necessary roles in your GCP project. > [!CAUTION] > > This permission policy is the minimum required for Cockroach Labs to provision, operate, patch, back up, and heal your cluster over its full lifecycle. This is not a temporary permission set used only at time of creation. > > Do **not** remove, narrow, or add conditions to these permissions after setup. Many of these permissions are used only during a specific lifecycle event, such as replacing a failed node, applying a patch, rotating an encryption key, or running a managed backup. Removing a permission might not cause an immediate error. A later operation that requires it, such as replacing a failed node or running a backup, can fail. Reducing the permission set voids the availability commitment for the cluster. > > Guardrails that restrict the account to particular regions or services, without touching the permissions the deployment requires, are compatible. Organization policies that restrict this permission set are not supported. Follow these steps to create the intermediate service account: 1. Open the GCP IAM Console. 2. Create a new service account. You can choose any name for this service account. Note its email address, which you need when you create the cluster. 3. Grant the following IAM roles to the service account: * `Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1)` * `Compute Network Admin (roles/compute.networkAdmin)` * `Compute Security Admin (roles/compute.securityAdmin)` * `Kubernetes Engine Admin (roles/container.admin)` * `Role Administrator (roles/iam.roleAdmin)` * `Service Account Admin (roles/iam.serviceAccountAdmin)` * `Service Account Key Admin (roles/iam.serviceAccountKeyAdmin)` * `Service Account Token Creator (roles/iam.serviceAccountTokenCreator)` * `Service Account User (roles/iam.serviceAccountUser)` * `Logs Configuration Writer (roles/logging.configWriter)` * `Project IAM Admin (roles/resourcemanager.projectIamAdmin)` * `Project Mover (roles/resourcemanager.projectMover)` * `Service Usage Admin (roles/serviceusage.serviceUsageAdmin)` * `Storage Admin (roles/storage.admin)` ## Step 4. Create the Continuum Cloud cluster In BYOC deployments, you can deploy CockroachDB clusters in the Cloud Console or with the [Cloud API](/docs/continuum/cloud-api). ### Create a cluster with the Cloud Console Follow these steps to create a Mission Critical cluster in the Cloud Console: 1. Open the Cloud Console and select the organization where BYOC is enabled. 2. Click **New cluster**. 3. For the edition, choose **Mission Critical**. BYOC is available only for the Mission Critical edition. 4. For the deployment, choose **Bring Your Own Cloud**, then select Google Cloud as the cloud provider. 5. Under **Cloud account**, select the cloud account you prepared, or add a new cloud account. Enter the service account email associated with the intermediate service account you created, *not* the email address of the Cockroach Labs service account. 6. Configure the cluster's regions, capacity, and add-ons as desired, then create the cluster. Refer to [Create a Cluster](/docs/continuum/create-a-cluster) and [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) for more details. ### Create a cluster with the Cloud API Send a `POST` request to the `/v1/clusters` endpoint of the [Cloud API](/docs/continuum/cloud-api) to create a Mission Critical cluster, specifying the appropriate `edition`. The following example request creates a 3-node Mission Critical cluster in the `us-east1` region, specifying the intermediate service account you created in the `service_account_email` field: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request POST \ --url https://cockroachlabs.cloud/api/v1/clusters \ --header "Authorization: Bearer {secret_key}" \ --json '{ "name": "byoc-gcp-cluster-1", "provider": "GCP", "spec": { "edition": "MISSION_CRITICAL", "customer_cloud_account": { "gcp": { "service_account_email": "{intermediate_service_account_email}" } }, "dedicated": { "hardware": { "machine_spec": { "num_virtual_cpus": 4 }, "storage_gib": 16 }, "region_nodes": { "us-east1": 3 } } } }' ``` ## Create additional BYOC clusters A GCP project prepared for BYOC can support multiple Continuum Cloud clusters. To create an additional BYOC cluster in the same project, follow the [Create the Continuum Cloud cluster](#step-4-create-the-continuum-cloud-cluster) steps again. ## Delete a BYOC cluster To delete a BYOC cluster, delete the cluster from the Cloud Console or with the [Cloud API](/docs/api/cloud/v1/clusters/delete-a-cluster-and-all-of-its-data). The Console steps are the same as for any Mission Critical cluster; refer to [Delete cluster](/docs/cockroachcloud/advanced-cluster-management#delete-cluster). Deleting the cluster is permanent and cannot be undone. When you delete a BYOC cluster, Cockroach Labs removes the managed resources that it provisioned in your GCP project for the cluster. The intermediate service account you created during setup is not removed automatically and remains under your control. You can remove it once deletion is complete. > [!CAUTION] > > Do not remove the intermediate service account or its permissions before deletion has finished. Cockroach Labs needs them to remove the managed resources from your GCP project. Removing access early can leave resources behind that you will need to clean up manually, and that will continue to incur charges from your cloud provider. ### Verify that deletion is complete After the cluster reports as deleted in the Cloud Console, verify that no managed resources remain in your GCP project. Review the GCP services covered by the IAM roles in Step 3 (for example, Compute Engine, Google Kubernetes Engine, and Cloud Storage) for resources associated with the cluster. If resources remain, contact your Cockroach Labs account team before removing them manually. ### Reuse the GCP project Before you reuse the GCP project for a subsequent BYOC deployment, verify that deletion of the previous cluster is complete and contact your Cockroach Labs account team to confirm that the project is ready for reuse. ## Next steps * [Connect to your cluster](/docs/continuum/connect-to-a-cluster) * [Manage your cluster using the Cloud API](/docs/continuum/cloud-api) * [Prepare your deployment for production](/docs/cockroachcloud/production-checklist) # Continuum Cloud BYOC Overview Source: https://docs.cockroachlabs.com/docs/continuum/byoc-overview Cockroach Continuum Cloud supports a [Bring Your Own Cloud (BYOC) deployment model](https://www.cockroachlabs.com/product/cloud/bring-your-own-cloud/), where a Mission Critical cluster is hosted in your own cloud account rather than in an account managed by Cockroach Labs. With BYOC, you control the cloud account's security configuration and can apply your existing cloud provider credits or discounts. ## BYOC in a Continuum Cloud organization BYOC is available on request for Continuum Cloud organizations that are billed by invoice. To enable BYOC for your organization, contact your Cockroach Labs account team. A BYOC cluster is fully managed by Cockroach Labs in the same way as a cluster in a Cockroach Labs account. It has the same feature set, including [physical cluster replication](/docs/continuum/physical-cluster-replication) and [changefeeds](/docs/continuum/changefeed-sinks), and the same [availability SLA](/docs/continuum/editions-and-add-ons#editions) as a Mission Critical cluster in a Cockroach Labs account. > [!NOTE] > > Host clusters and virtual clusters ([Cluster Virtualization](/docs/continuum/virtualization-overview)) are in [preview](/docs/continuum/feature-availability) and are not covered by the availability SLA. In a Continuum Cloud organization, BYOC works as follows: * BYOC clusters use the [Mission Critical edition](/docs/continuum/editions-and-add-ons#editions) with provisioned storage. The Standard edition and [usage-based storage](/docs/continuum/plenum-overview) are not available on BYOC. * You choose BYOC per cluster when you [create the cluster](/docs/continuum/create-a-cluster): after choosing the Mission Critical edition, choose **Bring Your Own Cloud** as the deployment option and select the cloud account that you prepared. On the **Clusters** page, a BYOC cluster's edition is shown as **Mission Critical (BYOC)**. * An organization can run BYOC clusters and clusters in Cockroach Labs accounts side by side. Each cluster is billed at its applicable rate, and credits are shared across the organization. An organization can also be restricted so that only BYOC clusters can be created in it. * [Cluster virtualization](/docs/continuum/virtualization-overview) on a BYOC cluster is in [preview](/docs/continuum/feature-availability) on AWS and GCP and is enabled on request. Refer to [Work with Virtual Clusters](/docs/continuum/virtual-clusters). ## Shared responsibility model for BYOC In any Continuum Cloud deployment, responsibility for a successful and healthy deployment is [split between you and Cockroach Labs](/docs/cockroachcloud/production-checklist). In a BYOC deployment, all of the cluster infrastructure except the control plane lives in an account under your control, which means that you incur additional responsibilities under the shared model. The following table describes the split of responsibilities between you and Cockroach Labs in the shared responsibility model for BYOC: | Area | Cockroach Labs responsibility | Customer responsibility | | :-: | :-: | :-: | | Uptime | Meet the [availability commitment](/docs/continuum/byoc-security#availability-commitment) for the CockroachDB cluster. Host clusters and virtual clusters are in [preview](/docs/continuum/feature-availability) and are not covered by the availability SLA | Ensure that clusters remain accessible to Cockroach Labs through cross-account IAM as documented in the corresponding [deployment guide](#next-steps) | | Deployments | Automate cluster provisioning and scaling, provide hardware best practices | Provision new cloud service accounts and grant IAM permissions for Cockroach Labs to create and manage clusters | | Upgrades | Provide automatic minor/patch upgrades and major upgrade automation via Terraform, APIs, or the Cloud Console | Initiate [major version upgrades](/docs/cockroachcloud/upgrade-cockroach-version), [set maintenance windows](/docs/cockroachcloud/advanced-cluster-management#set-a-maintenance-window) if applicable | | Workload | Troubleshoot problems as they pertain to cluster availability | [Size clusters](/docs/cockroachcloud/advanced-cluster-management#scale-your-cluster) to manage workload requirements, [tune performance](/docs/stable/performance-recipes), and adjust schema designs with support from Cockroach Labs | | Backups | Initialize a default backup schedule and write to customer-owned Cloud storage, ensure backup jobs run successfully | Configure a backup schedule as needed to meet RPO/RTO requirements | | Support | Reactively and proactively identify and resolve availability-impacting incidents | Ensure sufficient hardware is made available to prevent scaling issues, including negotiating cloud resource quotas and availability with your cloud service provider. Maintain appropriate IAM permissions at all times | | Billing | Meter the vCPUs the cluster consumes and charge for them at the BYOC rate, drawn from your organization's credits (refer to [Billing and metering](/docs/continuum/editions-and-add-ons#billing-and-metering)). For rates, contact your Cockroach Labs account team | Negotiate with cloud service provider, manage infrastructure spend and discounts. Cloud resources for the cluster are provisioned in your cloud account and billed directly by your cloud provider, including any discounts or commitments you have in place | ## Next steps To learn how the control plane interacts with a BYOC deployment and what data leaves your cloud account, refer to [BYOC Architecture and Data Flow](/docs/continuum/byoc-architecture). To learn about data and account security as well as the shared responsibility model in a BYOC deployment, refer to [Security and Compliance in BYOC](/docs/continuum/byoc-security). CockroachDB supports BYOC deployments in Amazon Web Services, Microsoft Azure, and Google Cloud Platform. To prepare your cloud account for a BYOC deployment, refer to the corresponding deployment guide: * [Prepare a Continuum Cloud BYOC Deployment in Amazon Web Services](/docs/continuum/byoc-aws-deployment) * [Prepare a Continuum Cloud BYOC Deployment in Azure](/docs/continuum/byoc-azure-deployment) * [Prepare a Continuum Cloud BYOC Deployment in Google Cloud Platform](/docs/continuum/byoc-gcp-deployment) Once you have prepared your cloud account for a BYOC deployment, cluster configuration and management is identical to a Mission Critical cluster in a Cockroach Labs account. To learn more about Mission Critical cluster planning and management, refer to the following guides: * [Create a Cluster](/docs/continuum/create-a-cluster) * [Plan a CockroachDB Advanced Cluster](/docs/cockroachcloud/plan-your-cluster-advanced) * [Manage a cluster using the Cloud API](/docs/continuum/cloud-api) * [Prepare a deployment for production](/docs/cockroachcloud/production-checklist) For answers to common questions about BYOC deployments, refer to the [Continuum Cloud BYOC FAQ](/docs/continuum/byoc-faq). # Security and Compliance in BYOC Source: https://docs.cockroachlabs.com/docs/continuum/byoc-security In a Bring Your Own Cloud (BYOC) deployment, you own the cloud account and Cockroach Labs operates the CockroachDB cluster inside it. This page describes the access Cockroach Labs has, how that access is constrained and audited, how you revoke it, and the compliance posture of the service. For information about the BYOC deployment model and the overall shared responsibility model, refer to the [Continuum Cloud BYOC Overview](/docs/continuum/byoc-overview). ## What Cockroach Labs can do in your cloud account During setup you grant Cockroach Labs a scoped cross-account identity: an IAM role on Amazon Web Services (AWS), a service principal on Microsoft Azure, or a service account on Google Cloud Platform (GCP). The permissions attached to that identity are published in full in the [deployment guide for each cloud](#next-steps). They are limited to the resources that make up the CockroachDB deployment: * The managed Kubernetes cluster. * Compute instances. * Block storage. * Load balancers and private endpoints. * The backup bucket. * Key management for cluster and backup encryption. * Networking configuration. * System databases for CockroachDB. * The service quotas the cluster depends on. Cockroach Labs does not have access to your broader corporate network, to other accounts or subscriptions in your organization, or to resources in the account that are unrelated to the deployment. For strong isolation, Cockroach Labs recommends creating a new AWS account, Azure subscription, or GCP project for CockroachDB BYOC, so that its cluster resources are isolated from your applications and other organizational infrastructure. Automated control plane operations do not take any destructive actions, such as cluster deletion. ## Why the permissions cannot be reduced The published permission set is the minimum required for the control plane to provision, operate, patch, back up, and heal a CockroachDB cluster over its full lifecycle. The list is not a setup-time permission set. It is required for Cockroach Labs to meet cluster uptime SLAs. > [!WARNING] > > Do not remove, narrow, or condition the permissions after setup. Many of the permissions are exercised only during a specific lifecycle event, such as replacing a failed node, applying a patch, rotating an encryption key, or running a managed backup. Removing a permission might not cause an immediate error. A later operation that requires it can fail, often weeks later and during an incident. Reducing the permission set voids the availability commitment for the cluster. > > On AWS accounts, do not use resources that can affect the control plane's ability to operate on CockroachDB clusters. The following are not supported: * **Reducing the permission set**, including scoping a production deployment more tightly than a non-production one. If you want production and non-production deployments to have separate identities and separate blast radius, deploy them into separate cloud accounts. Each cloud account has its own cross-account identity and its own permission set. * **Applying conditional or time-bounded policies**, including policies that deny actions outside a maintenance window. The control plane must be able to act on a cluster health signal at any time. A restriction window that coincides with a node failure can leave the cluster degraded. * **Applying service control policies or organization policies that restrict the required permission set.** Guardrails that constrain the account to particular regions or services, without touching the permissions the deployment requires, are compatible. * **Imposing a change freeze on the cross-account identity.** ## Human access Cockroach Labs engineers have no standing access to customer cloud accounts. To act in a customer account, an engineer must request eligibility through a privileged access management workflow with a recorded justification. Access is granted just in time, is scoped to a specific account, and expires. All access is authenticated through the Cockroach Labs enterprise identity provider with multi-factor authentication, and can only be run on a corporate device in compliance with Cockroach Labs' device policy. Because no engineer holds a persistent entitlement, offboarding does not depend on a separate revocation step. When a Cockroach Labs employee leaves, their identity provider account is deactivated through an HR-driven workflow within one business day of termination, and there is no standing grant to remove. Eligibility to request escalated access is itself restricted to a defined engineering group, and being in that group does not grant access. It grants only the ability to request it. ## Audit Cockroach Labs access Every action Cockroach Labs takes in your cloud account is an authenticated cloud provider API call, so it is recorded in your own cloud provider audit log. You do not need to request logs from Cockroach Labs to review the actions Cockroach Labs has taken. On AWS, every role assumption is recorded in AWS CloudTrail with a grant-specific role session name, a source identity, and session tags that encode the requesting engineer's identity and justification. To review all Cockroach Labs activity, filter CloudTrail on the ARN of the role you created: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} userIdentity.sessionContext.sessionIssuer.arn = "arn:aws:iam::{AWS account ID}:role/{BYOC role name}" ``` You can alert on this activity in real time by using Amazon EventBridge rules or Amazon CloudWatch alarms. On Azure, activity performed by the service principal is recorded in the Azure Activity Log for the subscription. On GCP, it is recorded in Cloud Audit Logs for the project. > [!NOTE] > > Session identifiers in your audit log encode the grant, not the individual's name. If you require attribution of a specific session to a named Cockroach Labs individual, contact Cockroach Labs support with the session identifier. ## Revoke access You can revoke Cockroach Labs access at any time and without notice by removing the trust relationship on the role, deleting the service principal, or attaching a deny-all policy. Revocation takes effect immediately. The following stops when access is revoked: * Provisioning, scaling, and configuration changes. * Patching and version upgrades. * Managed backup orchestration. * Automated healing, including replacement of a failed node. * Monitoring, alerting, and support's ability to diagnose the cluster. * The availability commitment for the cluster. The following continues: * SQL traffic. The cluster keeps serving your applications. * Raft replication and consensus. Restoring access restores management. If you are considering revocation in response to a security concern, contact Cockroach Labs support first. ## Encryption The following forms of encryption are used in a BYOC deployment: * **In transit:** Traffic between CockroachDB nodes uses TLS 1.3. Client and application connections use TLS 1.2 or TLS 1.3. Data sent from your cloud account to Cockroach Labs is encrypted in transit. * **At rest:** Cluster storage is encrypted at the infrastructure level using your cloud provider's disk encryption. This applies whether or not you configure anything further. You can additionally enable customer-managed encryption keys (CMEK), which are supported with AWS KMS, Google Cloud KMS, and Azure Key Vault. CMEK applies both to cluster-level encryption and to the encryption of managed backups. Key material remains in your own cloud account and under your control at all times. Refer to [Customer-Managed Encryption Keys (CMEK)](/docs/continuum/cmek). * **Backups:** Managed backups are written to a storage bucket in your own cloud account and encrypted with a key you control. ## Compliance The following applies to the BYOC service specifically. Reports are available under a non-disclosure agreement (NDA) through your Cockroach Labs account team. | Framework | Status | | - | - | | SOC 2 Type I | Report available under NDA. | | SOC 2 Type II | Readiness letter available under NDA. Report delivery is targeted for December 18, 2026. | | ISO/IEC 27001:2022 | Cockroach Labs is certified. The certificate is publicly available in the [Cockroach Labs Trust Center](https://www.cockroachlabs.com/trust-center/). The scope includes cloud service provider controls (ISO/IEC 27017:2015) and PII controls (ISO/IEC 27018:2019). | | PCI DSS | CockroachDB BYOC is compliant as a Level 1 Service Provider. | | Penetration testing | Cockroach Labs commissions an annual third-party penetration test. A summary is available under NDA. | ### Data protection Row-level data in a BYOC cluster remains in your own cloud account, in the region you select, and Cockroach Labs does not process it. Operational telemetry and redacted logs, which contain no personal data or payment data, are processed by Cockroach Labs in the United States. Because you control the data in your clusters, you remain responsible for its classification and retention, and for responding to data subject requests relating to it. For personal data Cockroach Labs processes as part of the commercial relationship, refer to the [Cockroach Labs Data Processing Addendum](https://www.cockroachlabs.com/cloud-terms-and-conditions/data-processing-addendum/). ## Shared responsibility for security The following table describes the split of security responsibilities between you and Cockroach Labs: | Area | Cockroach Labs | You | | - | - | - | | Hardening of the CockroachDB deployment: node images, the Kubernetes layer, CockroachDB configuration | Yes | No | | Account-level guardrails, organization policies, and security tooling in your cloud account | No | Yes | | Maintaining the cross-account identity, its permissions, and the service quotas the cluster depends on | No | Yes | | Patching and upgrading CockroachDB and the managed infrastructure | Yes | No | | SQL-level authentication, authorization, and audit logging inside the database | No | Yes | | Classification, retention, and deletion of data in the cluster | No | Yes | | Monitoring, alerting, and incident response for the managed cluster | Yes | No | ## Availability commitment The availability commitment for a BYOC deployment applies to the CockroachDB cluster and is the same [availability SLA](/docs/continuum/editions-and-add-ons#editions) as for a Mission Critical cluster in a Cockroach Labs account. Host clusters and virtual clusters ([Cluster Virtualization](/docs/continuum/virtualization-overview)) are in [preview](/docs/continuum/feature-availability) and are not covered by the availability SLA. Cockroach Labs does not publish a separate uptime commitment for the control plane. The control plane has a recovery time objective of 4 hours, its status is published at [status.cockroachlabs.cloud](https://status.cockroachlabs.cloud/), and a control plane outage does not interrupt SQL traffic. The commitment does not apply if the cross-account identity or its permissions are removed or restricted, if required service quotas are exhausted, or if managed resources in the account are modified outside of Cockroach Labs. ## Next steps * [Review the Continuum Cloud BYOC Overview](/docs/continuum/byoc-overview). * [Prepare a BYOC deployment in Amazon Web Services](/docs/continuum/byoc-aws-deployment). * [Prepare a BYOC deployment in Azure](/docs/continuum/byoc-azure-deployment). * [Prepare a BYOC deployment in Google Cloud Platform](/docs/continuum/byoc-gcp-deployment). # ccloud CLI Source: https://docs.cockroachlabs.com/docs/continuum/ccloud-get-started # Changefeed Sinks Source: https://docs.cockroachlabs.com/docs/continuum/changefeed-sinks # Cloud API Source: https://docs.cockroachlabs.com/docs/continuum/cloud-api # Cluster Management Source: https://docs.cockroachlabs.com/docs/continuum/cluster-management # CMEK Source: https://docs.cockroachlabs.com/docs/continuum/cmek # Architecture Source: https://docs.cockroachlabs.com/docs/continuum/cockroachdb-architecture # CockroachDB Documentation Source: https://docs.cockroachlabs.com/docs/continuum/cockroachdb-get-started # SQL Reference Source: https://docs.cockroachlabs.com/docs/continuum/cockroachdb-sql # Transactions Source: https://docs.cockroachlabs.com/docs/continuum/cockroachdb-transactions # Connect to a Cluster Source: https://docs.cockroachlabs.com/docs/continuum/connect-to-a-cluster # Connection Parameters Source: https://docs.cockroachlabs.com/docs/continuum/connection-parameters # Create a Cluster Source: https://docs.cockroachlabs.com/docs/continuum/create-a-cluster You can create a cluster in a Cockroach Continuum Cloud organization by picking an edition, a deployment, a cloud provider, regions, and a storage model. ## Choose an edition Continuum Cloud offers the Standard and Mission Critical editions. The edition sets the cluster's infrastructure, availability, and feature boundaries, and it is permanent for the cluster. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons#choose-an-edition) for more information. ## Choose a deployment A cluster runs either in a cloud account managed by Cockroach Labs or, with [Bring Your Own Cloud (BYOC)](/docs/continuum/byoc-overview), in your own AWS, Azure, or GCP account. BYOC is available on request for organizations billed by invoice, and only for Mission Critical clusters with provisioned storage. If BYOC is enabled for your organization, choose **Bring Your Own Cloud** as the deployment when you create a Mission Critical cluster, and select a cloud account that you have [prepared for BYOC](/docs/continuum/byoc-overview#next-steps). ## Choose a storage model The storage model is set when you create a cluster. Single-region Mission Critical clusters offer a choice of storage model: usage-based storage (in preview) or provisioned storage. Multi-region Mission Critical clusters use provisioned storage, and Standard clusters run on shared infrastructure with usage-based storage billing. Refer to [Cockroach Plenum](/docs/continuum/plenum-overview) for information about usage-based storage. Mission Critical clusters with usage-based storage must run CockroachDB v26.3 or later. Plenum-backed Mission Critical clusters are available in the following AWS regions: * `us-east-1` * `us-west-2` * `eu-central-1` * `eu-west-1` Standard clusters run on shared infrastructure with usage-based storage billing, separate from Plenum. For supported regions, refer to the Standard tab in [CockroachDB Cloud Regions](/docs/cockroachcloud/regions). ## Enable virtualization To run [virtual clusters](/docs/continuum/virtual-clusters), enable virtualization when you create a Mission Critical cluster with provisioned storage at this time. This choice is available only at creation: an existing cluster cannot be converted into a host. For what a host provides and how virtual clusters share it, refer to the [virtualization overview](/docs/continuum/virtualization-overview). Requires the [Cluster Virtualization add-on](/docs/continuum/editions-and-add-ons#add-ons). ## Select add-ons Add-ons that you select at creation are billed on the cluster while active; there is no separate enablement step. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons#add-ons) for more information. After creation, refer to [Cluster Management](/docs/continuum/cluster-management), or continue with the [Quickstart with Cockroach Continuum Cloud](/docs/continuum/tutorial-quickstart) to connect to your cluster and run your first queries. # Create a Continuum Cloud Organization Source: https://docs.cockroachlabs.com/docs/continuum/create-a-continuum-organization Cockroach Continuum Cloud is the latest generation of CockroachDB's fully-managed service. New CockroachDB Cloud organizations created as of September 15, 2026 use Continuum Cloud by default, so signing up creates one automatically. ## Create your organization Create a new Continuum Cloud organization with the [CockroachDB Cloud sign-up page](https://cockroachlabs.cloud/signup). New CockroachDB Cloud accounts are automatically created as Continuum Cloud organizations. You can register with Single Sign-On (SSO) or with an email address and password. For the full set of authentication options, including SSO providers and multi-factor authentication, refer to [Create a CockroachDB Cloud account](/docs/cockroachcloud/create-an-account). > [tab] Use SSO > > 1. On the registration page, click **Sign up with...** for your SSO provider. > 2. Accept the terms of service and privacy policy. > 3. Complete sign-in with your SSO provider and authorize CockroachDB Cloud. > > Your Continuum Cloud organization is created and the Cloud Console opens. > [tab] Use email > > 1. On the registration page, click **Sign up with email**. > 2. Enter an email address and password, then accept the terms of service and privacy policy. > 3. Check your email for a message from Cockroach Labs and click **Verify my email**. > 4. Enter your name and company details, then complete the onboarding survey. > > Your Continuum Cloud organization is created and the Cloud Console opens. ## Existing Cloud organizations If you have an existing CockroachDB Cloud organization and are interested in moving to Continuum Cloud, contact your Cockroach Labs account team. ## Next steps * [Create a cluster](/docs/continuum/create-a-cluster). You choose an edition and a storage model when you create a cluster, and both are permanent for that cluster. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons) to choose an edition. * Continue with the [Quickstart with Cockroach Continuum Cloud](/docs/continuum/tutorial-quickstart) to connect to your cluster and run your first queries. # DB Console Source: https://docs.cockroachlabs.com/docs/continuum/db-console # Deploy and Manage Overview Source: https://docs.cockroachlabs.com/docs/continuum/deploy-and-manage-overview Deploy Cockroach Continuum Cloud by creating clusters in a Continuum Cloud organization, and manage them through the Cloud Console, the Cloud API, Terraform, or the `ccloud` CLI. A cluster's edition and [storage model](/docs/continuum/plenum-overview#usage-based-storage) are chosen when you create it. You can also deploy a Mission Critical cluster with **Bring Your Own Cloud (BYOC)**, where the cluster is hosted in your own cloud account rather than in an account managed by Cockroach Labs. Pages in this section: * [BYOC Deployments](/docs/continuum/byoc-overview) * [Create a Cluster](/docs/continuum/create-a-cluster) * [Cluster Management](/docs/continuum/cluster-management) * [Cloud API](/docs/cockroachcloud/cloud-api) * [ccloud CLI](/docs/cockroachcloud/ccloud-get-started) # Develop and Connect Overview Source: https://docs.cockroachlabs.com/docs/continuum/develop-and-connect-overview Applications connect to a Cockroach Continuum Cloud cluster with standard PostgreSQL drivers and tools. Each cluster has its own PostgreSQL connection string and SQL users, and applications use the same CockroachDB SQL dialect, functions, and procedural extensions. You can also connect AI tools to Continuum Cloud with the [CockroachDB MCP server](/docs/stable/cockroachdb-mcp-server). Pages in this section: * [Connect to a Cluster](/docs/cockroachcloud/connect-to-your-cluster) * [Connection Parameters](/docs/stable/connection-parameters) * [Transactions](/docs/stable/transactions) * [User-Defined Functions](/docs/stable/user-defined-functions) * [Stored Procedures](/docs/stable/stored-procedures) * [Triggers](/docs/stable/triggers) ## Connection routing A standalone cluster has its own connection string and SQL users. To retrieve the connection string and create users, refer to [Connect to a Cluster](/docs/cockroachcloud/connect-to-your-cluster). On a host cluster, each [virtual cluster](/docs/continuum/virtualization-overview) has its own PostgreSQL connection string and SQL users, and connections route only to that virtual cluster. An application connected to one virtual cluster cannot see or reach the host or any other virtual cluster on it. To connect, refer to [Connect to a virtual cluster](/docs/continuum/virtual-clusters#connect-to-a-virtual-cluster). ## Drivers, ORMs, and connection pooling Because Continuum Cloud clusters are wire-compatible with PostgreSQL, applications connect using standard PostgreSQL drivers and object-relational mapping (ORM) frameworks. To choose and install a client library, refer to [Install a Driver or ORM Framework](/docs/stable/install-client-drivers). For production workloads, use a pool of persistent connections rather than opening a new connection per request. Refer to [Connection Pooling](/docs/stable/connection-pooling) for more information. ## AI tools Continuum Cloud is designed to support AI development and management. Use the [CockroachDB Cloud MCP Server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server) to enable agents to access clusters in your organization. Continuum [virtualization](/docs/continuum/virtualization-overview) allows you to deploy a dedicated host cluster, then agents and application developers can deploy virtual clusters with minimal overhead. Read the [Build Your First Virtual Cluster](/docs/continuum/tutorial-virtual-cluster) tutorial for agent guidance. # Disaster Recovery Overview Source: https://docs.cockroachlabs.com/docs/continuum/disaster-recovery-overview > [!NOTE] > > **Physical Cluster Replication in Cockroach Continuum Cloud is in [limited access](/docs/releases/cockroachdb-feature-availability)** and only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team. Continuum Cloud clusters replicate data across nodes for availability, and managed backups provide recovery points for every cluster. Mission Critical clusters can additionally replicate to a standby cluster with physical cluster replication, enabled by the [Data Replication add-on](/docs/continuum/editions-and-add-ons#add-ons). Pages in this section: * [Managed Backups](/docs/cockroachcloud/managed-backups) * [Physical Cluster Replication](/docs/cockroachcloud/physical-cluster-replication) # Editions and Add-Ons Source: https://docs.cockroachlabs.com/docs/continuum/editions-and-add-ons Cockroach Continuum Cloud offers CockroachDB in *editions*, cluster plans that set infrastructure, availability, and feature boundaries. [*Add-ons*](#add-ons) enable additional capabilities on a cluster. There is no separate purchase step for an add-on: when you use an add-on feature, it appears as a line item on your bill for the time it's active. ## Editions The editions differ first in infrastructure. *Shared* infrastructure serves clusters from multiple organizations. *Dedicated* infrastructure is provisioned for a single cluster. Continuum Cloud offers two editions: * *Standard* runs production workloads on shared infrastructure, in single-region or multi-region configurations, with usage-based storage billing and a 99.99% availability SLA. * *Mission Critical* runs on dedicated infrastructure for workloads that need the highest availability and the full security feature set, with a 99.999% SLA for multi-region configurations and region-level resiliency options. Single-region Mission Critical clusters choose [usage-based](/docs/continuum/plenum-overview) or provisioned storage at creation. You choose an edition when you create a cluster, and the choice is permanent for that cluster: to change editions, you create a new cluster and move the workload. A Mission Critical cluster with provisioned storage can also run in your own cloud account with [Bring Your Own Cloud (BYOC)](/docs/continuum/byoc-overview). ### Choose an edition Choose Standard for workloads that tolerate shared infrastructure and do not need features available only on Mission Critical clusters, such as [CMEK](/docs/continuum/cmek) or [physical cluster replication](/docs/continuum/physical-cluster-replication). Choose Mission Critical for Tier 0 and regulated workloads, for the strictest recovery objectives, and for any cluster that will host [virtual clusters](/docs/continuum/virtual-clusters). ## Feature reference To view CockroachDB feature availability by edition and on virtual clusters, refer to [Feature Reference](/docs/continuum/feature-reference). ## Add-ons Add-ons are not installed or enabled separately. Creating a host cluster, starting physical replication, or creating a changefeed to a sink starts the add-on charge, and stopping use stops it. Add-ons are scoped to the cluster that uses them, with one exception noted in the below table. | Add-on | Description | | - | - | | Cluster Virtualization | Enables a Mission Critical cluster to act as a host for virtual clusters. Chosen at [cluster creation](/docs/continuum/create-a-cluster). Refer to the [virtualization overview](/docs/continuum/virtualization-overview) and [Workspaces](/docs/continuum/workspaces). | | Data Replication ([Limited Access](/docs/continuum/feature-availability)) | Enables physical cluster replication between Mission Critical clusters for cluster-level [disaster recovery](/docs/continuum/disaster-recovery-overview). Refer to the [physical cluster replication](/docs/v26.3/physical-cluster-replication-overview) documentation. | | Data Sync | Enables changefeeds to external sinks such as Kafka and cloud storage as part of [integrating](/docs/continuum/integrate-overview) with your stack, and is the one add-on available on Standard clusters. Sinkless changefeeds are not part of the add-on boundary. Refer to the [change data capture](/docs/v26.3/change-data-capture-overview) documentation. | | Advanced Compliance | Grants access to the Trust Center. The exception to cluster-level scoping: it applies at the organization level, across the organization's Mission Critical clusters. | ## Feature entitlements and license behavior Feature boundaries are enforced by the database itself through license entitlements. If a statement requires a feature your cluster's plan does not include, it fails with an error of the following form: ``` : this feature is not included in your license. Contact sales@cockroachlabs.com to learn more. ``` Enforcement behavior: * Physical cluster replication is checked on both the source and the destination cluster. * Logical data replication requires the entitlement on both clusters. * Changefeeds to sinks are gated. Sinkless changefeeds are not. * The `feature.changefeed.enabled` cluster setting is an independent operator control and is unrelated to license entitlements. * Several license-gateable features are deliberately included on Standard for PostgreSQL compatibility, including point-in-time restore, row-level security, column-level encryption, changefeeds, and `EXPORT`. * Clusters without a new-format license, and clusters on older CockroachDB versions, are not subject to entitlement enforcement. ## Billing and metering Continuum Cloud bills in credits. Compute is metered in vCPU-hours. Storage charges depend on the edition and storage model. Standard clusters use usage-based storage billing. Plenum-backed Mission Critical clusters are billed for physical data stored, while provisioned Mission Critical clusters are billed for provisioned capacity. Network and backup storage costs are passed through from the cloud provider based on usage. For a [BYOC](/docs/continuum/byoc-overview) cluster, Cockroach Labs meters and charges for compute at the BYOC rate. The cloud resources themselves, including storage, network, and backup storage, are provisioned in your own cloud account and billed directly by your cloud provider. Add-on charges appear as separate line items on the clusters that use them, for the time the feature is active. An add-on's charge is a multiplier on the compute rate, applied to the vCPU-hours during which the feature is active. The base compute and each add-on appear as their own invoice lines, so the charge tracks when the feature was in use. Marketplace billing through AWS and GCP is supported, and new organizations receive free trial credits. For rates, refer to [Pricing](https://www.cockroachlabs.com/pricing). # Export Metrics Source: https://docs.cockroachlabs.com/docs/continuum/export-metrics # Continuum Cloud FAQ Source: https://docs.cockroachlabs.com/docs/continuum/faq Answers to common questions about Cockroach Continuum Cloud. ## About Continuum Cloud ### What is Cockroach Continuum Cloud? Cockroach Continuum Cloud is an agentic database cloud built on CockroachDB: a platform with [virtualization](/docs/continuum/virtualization-overview), [usage-based storage](/docs/continuum/plenum-overview), [a managed monitoring agent](/docs/continuum/aegis-overview), and an [AI-guided migration workflow](/docs/continuum/migration-assistant-overview). Refer to the [overview](/docs/continuum/overview). ### How does Continuum Cloud relate to CockroachDB and CockroachDB Cloud? Continuum Cloud is built on CockroachDB. Every cluster on Continuum Cloud is a CockroachDB cluster, and CockroachDB documentation applies to SQL and database behavior on every Continuum Cloud cluster. Continuum Cloud is enabled per organization: new CockroachDB Cloud organizations use Continuum Cloud, and the same user can belong to Continuum Cloud and other Cloud organizations. Existing clusters continue to run in their existing Cloud configurations and are not automatically migrated to Continuum Cloud. ### Is Continuum Cloud available for self-hosted deployments? No. Continuum Cloud is a fully managed service that runs on CockroachDB Cloud. However, [Cockroach Aegis](/docs/continuum/aegis-overview) can monitor both Cloud and self-hosted CockroachDB clusters, whether or not they use Continuum Cloud. ## Agents and AI ### Is Aegis optional? Yes. Aegis is in private preview and requires sign-up and opt-in to connect a cluster. For connection requirements, see [How do I connect a cluster?](/docs/continuum/aegis-security-and-data-access#how-do-i-connect-a-cluster). ### Can Aegis modify my data or schema? No. Aegis's access to the monitored cluster is read-only. You review its recommendations and apply any changes through your normal change process. For more information, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). ### How does Aegis fit alongside monitoring tools like Datadog or Prometheus? Aegis complements those tools with CockroachDB-specific reports, investigations, and recommendations. For how Aegis builds context about a cluster over time, see [Automatic monitoring through Check-ins](/docs/continuum/aegis-overview#automatic-monitoring-through-check-ins). ## Editions, clusters, and features ### Which edition should I choose? Choose Standard for production workloads that run well on shared infrastructure. Choose Mission Critical for dedicated infrastructure, the strictest recovery objectives, the full security feature set, and hosting virtual clusters. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). ### Can I change a cluster's edition later? No. Editions are chosen at cluster creation. To change editions, create a new cluster and move the workload. ### What are virtual clusters, and what do they cost? A virtual cluster is an isolated database created on a [host cluster](/docs/continuum/workspaces) and served by the host's nodes. Virtual clusters carry no separate charge: you pay for the host and [Cluster Virtualization](/docs/continuum/editions-and-add-ons#add-ons) add-on, and virtual clusters share the host's capacity. Refer to [Work with Virtual Clusters](/docs/continuum/virtual-clusters). ### Can I use Bring Your Own Cloud in a Continuum Cloud organization? Yes. With [Bring Your Own Cloud (BYOC)](/docs/continuum/byoc-overview), a Mission Critical cluster runs in your own AWS, Azure, or GCP account while Cockroach Labs operates it. BYOC is available on request for organizations billed by invoice. For common questions, refer to the [BYOC FAQ](/docs/continuum/byoc-faq). ### Are all CockroachDB features available on Continuum Cloud? Feature availability depends on the cluster's edition and add-ons. If a statement requires a feature your cluster's plan does not include, it fails with an error that names the feature and directs you to contact Cockroach Labs. Refer to the [feature reference](/docs/continuum/feature-reference). ### What is usage-based storage? Usage-based storage bills for the data you store rather than the capacity you provision. Clusters with usage-based billing show consumption rather than capacity in the Console. Standard clusters run on shared infrastructure with usage-based storage billing. Single-region Mission Critical clusters can choose [Plenum-backed usage-based storage](/docs/continuum/plenum-overview) at cluster creation. This storage model is in [preview](/docs/continuum/feature-availability). Multi-region Mission Critical clusters and [host clusters](/docs/continuum/virtual-clusters) use provisioned storage. ### Can I change a cluster's storage model later? No. Single-region Mission Critical clusters choose a storage model at creation. To change storage models, create a new cluster and move the workload. ### Which cloud providers and regions does each edition support? Standard clusters run on AWS and GCP in a subset of regions. Mission Critical clusters run on AWS, GCP, and Azure in every region listed below. | Cloud | Region | Standard | Mission Critical | | - | - | - | - | | AWS | N. Virginia (us-east-1) | ✓ | ✓ | | AWS | Ohio (us-east-2) | ✓ | ✓ | | AWS | Oregon (us-west-2) | ✓ | ✓ | | AWS | Central Canada (ca-central-1) | ✗ | ✓ | | AWS | Calgary (ca-west-1) | ✗ | ✓ | | AWS | Sao Paulo (sa-east-1) | ✗ | ✓ | | AWS | Ireland (eu-west-1) | ✓ | ✓ | | AWS | London (eu-west-2) | ✓ | ✓ | | AWS | Paris (eu-west-3) | ✗ | ✓ | | AWS | Frankfurt (eu-central-1) | ✓ | ✓ | | AWS | Stockholm (eu-north-1) | ✗ | ✓ | | AWS | Milan (eu-south-1) | ✗ | ✓ | | AWS | Mumbai (ap-south-1) | ✓ | ✓ | | AWS | Singapore (ap-southeast-1) | ✓ | ✓ | | AWS | Jakarta (ap-southeast-3) | ✓ | ✓ | | AWS | Sydney (ap-southeast-2) | ✗ | ✓ | | AWS | Tokyo (ap-northeast-1) | ✗ | ✓ | | AWS | Osaka (ap-northeast-3) | ✗ | ✓ | | AWS | Seoul (ap-northeast-2) | ✗ | ✓ | | AWS | Hong Kong (ap-east-1) | ✗ | ✓ | | AWS | Bahrain (me-south-1) | ✗ | ✓ | | AWS | UAE Central (me-central-1) | ✗ | ✓ | | AWS | Tel Aviv (il-central-1) | ✗ | ✓ | | AWS | Cape Town (af-south-1) | ✗ | ✓ | | GCP | Iowa (us-central1) | ✓ | ✓ | | GCP | South Carolina (us-east1) | ✓ | ✓ | | GCP | N. Virginia (us-east4) | ✗ | ✓ | | GCP | Columbus (us-east5) | ✗ | ✓ | | GCP | Dallas (us-south1) | ✗ | ✓ | | GCP | Oregon (us-west1) | ✗ | ✓ | | GCP | California (us-west2) | ✓ | ✓ | | GCP | Salt Lake City (us-west3) | ✗ | ✓ | | GCP | Las Vegas (us-west4) | ✗ | ✓ | | GCP | Montreal (northamerica-northeast1) | ✗ | ✓ | | GCP | Toronto (northamerica-northeast2) | ✗ | ✓ | | GCP | Sao Paulo (southamerica-east1) | ✓ | ✓ | | GCP | Belgium (europe-west1) | ✓ | ✓ | | GCP | London (europe-west2) | ✓ | ✓ | | GCP | Frankfurt (europe-west3) | ✓ | ✓ | | GCP | Eemshaven (europe-west4) | ✗ | ✓ | | GCP | Zurich (europe-west6) | ✗ | ✓ | | GCP | Milan (europe-west8) | ✗ | ✓ | | GCP | Paris (europe-west9) | ✗ | ✓ | | GCP | Turin (europe-west12) | ✗ | ✓ | | GCP | Warsaw (europe-central2) | ✗ | ✓ | | GCP | Hamina (europe-north1) | ✗ | ✓ | | GCP | Madrid (europe-southwest1) | ✗ | ✓ | | GCP | Mumbai (asia-south1) | ✓ | ✓ | | GCP | Delhi (asia-south2) | ✗ | ✓ | | GCP | Singapore (asia-southeast1) | ✓ | ✓ | | GCP | Jakarta (asia-southeast2) | ✗ | ✓ | | GCP | Taiwan (asia-east1) | ✗ | ✓ | | GCP | Hong Kong (asia-east2) | ✗ | ✓ | | GCP | Tokyo (asia-northeast1) | ✗ | ✓ | | GCP | Osaka (asia-northeast2) | ✗ | ✓ | | GCP | Seoul (asia-northeast3) | ✗ | ✓ | | GCP | Sydney (australia-southeast1) | ✗ | ✓ | | GCP | Melbourne (australia-southeast2) | ✗ | ✓ | | GCP | Doha (me-central1) | ✗ | ✓ | | GCP | Dammam (me-central2) | ✗ | ✓ | | GCP | Tel Aviv (me-west1) | ✗ | ✓ | | Azure | Virginia (eastus) | ✗ | ✓ | | Azure | Virginia (eastus2) | ✗ | ✓ | | Azure | Iowa (centralus) | ✗ | ✓ | | Azure | Texas (southcentralus) | ✗ | ✓ | | Azure | Washington (westus2) | ✗ | ✓ | | Azure | Arizona (westus3) | ✗ | ✓ | | Azure | Toronto (canadacentral) | ✗ | ✓ | | Azure | Ireland (northeurope) | ✗ | ✓ | | Azure | Netherlands (westeurope) | ✗ | ✓ | | Azure | London (uksouth) | ✗ | ✓ | | Azure | Frankfurt (germanywestcentral) | ✗ | ✓ | | Azure | Paris (francecentral) | ✗ | ✓ | | Azure | Gävle (swedencentral) | ✗ | ✓ | | Azure | Oslo (norwayeast) | ✗ | ✓ | | Azure | Warsaw (polandcentral) | ✗ | ✓ | | Azure | Zürich (switzerlandnorth) | ✗ | ✓ | | Azure | Pune (centralindia) | ✗ | ✓ | | Azure | Singapore (southeastasia) | ✗ | ✓ | | Azure | Hong Kong (eastasia) | ✗ | ✓ | | Azure | Tokyo (japaneast) | ✗ | ✓ | | Azure | Seoul (koreacentral) | ✗ | ✓ | | Azure | New South Wales (australiaeast) | ✗ | ✓ | | Azure | New Zealand (newzealandnorth) | ✗ | ✓ | | Azure | Dubai (uaenorth) | ✗ | ✓ | | Azure | Johannesburg (southafricanorth) | ✗ | ✓ | ## Migrations ### How do I migrate to Continuum Cloud? For PostgreSQL and MySQL sources, use the [Migration Assistant](/docs/continuum/migration-assistant-overview), which guides schema conversion, data load, and verification. The Assistant's target must be a [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster. It cannot target Standard clusters or BYOC destinations. For other sources and for replication-based cutover, use the [MOLT toolset](/docs/molt/migration-overview). # Feature Availability Source: https://docs.cockroachlabs.com/docs/continuum/feature-availability Some features are made available in phases prior to being launched in general availability (GA). This page defines the different levels of product feature availability. This page outlines *feature availability*, which is separate from Cockroach Labs' [Release Support Policy](/docs/releases/release-support-policy) or [API Support Policy](/docs/stable/api-support-policy). ## Feature availability phases | Phase | Definition | Accessibility | | - | - | - | | Private preview | Feature is available to select customers and may not be publicly documented. | Invite-only | | Limited access | Feature is publicly documented but not yet available widely. This feature may have limitations and/or capabilities that may change or be added based on feedback, before being promoted to GA. | Opt-in Contact your Cockroach Labs account team. | | Preview | Feature is publicly available and documented. This feature may have limitations and/or capabilities that may change or be added based on feedback, before being promoted to GA. | Public | | General availability (GA) | Feature is publicly available and documented. | Public | Any feature made available in a phase prior to GA is provided without any warranties of any kind. Such features are not subject to any technical support or uptime availability commitments unless Cockroach Labs explicitly states otherwise in writing. For the availability phase of each Continuum feature, refer to the [feature reference](/docs/continuum/feature-reference). # Feature Reference Source: https://docs.cockroachlabs.com/docs/continuum/feature-reference This page summarizes feature availability across Cockroach Continuum Cloud editions and virtual clusters. For what editions and add-ons are and how they bill, refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). ## Features by edition | Feature | Standard | Mission Critical | | - | - | - | | Infrastructure | Shared | Dedicated | | Region topology | Single or multi-region | Single or multi-region (usage-based storage is single-region only) | | Clouds | AWS, GCP | AWS, GCP, Azure ([usage-based storage](/docs/continuum/plenum-overview#usage-based-storage) is available in selected AWS regions) | | Storage model | Usage-based | Provisioned, or [usage-based](/docs/continuum/plenum-overview) on single-region clusters running CockroachDB v26.3 or later | | Availability SLA | 99.99% | 99.99% single-region, 99.999% multi-region | | Support response SLA | 1-hour P1 | 30-minute P1 | | [Backups with revision history and PITR](/docs/stable/take-backups-with-revision-history-and-restore-from-a-point-in-time) | ✓ | ✓ | | [Managed backups and restore](/docs/cockroachcloud/managed-backups) | ✓ | ✓ | | [Encrypted backups](/docs/stable/take-and-restore-encrypted-backups) | ✓ | ✓ | | [Online restore](/docs/stable/restore) | ✗ | ✓ | | Host for [virtual clusters](/docs/continuum/virtual-clusters) | ✗ | ✓ (with the [Cluster Virtualization](/docs/continuum/editions-and-add-ons#add-ons) add-on; provisioned storage only) | | [Changefeeds (CDC)](/docs/stable/change-data-capture-overview) | ✓ (with the [Data Sync](/docs/continuum/editions-and-add-ons#add-ons) add-on) | ✓ (with the [Data Sync](/docs/continuum/editions-and-add-ons#add-ons) add-on) | | [`EXPORT`](/docs/stable/export) | ✓ | ✓ | | [Physical cluster replication](/docs/stable/physical-cluster-replication-overview) | ✗ | ✓ (with the [Data Replication](/docs/continuum/editions-and-add-ons#add-ons) add-on; [limited access](/docs/releases/cockroachdb-feature-availability), provisioned storage only) | | [Logical data replication](/docs/stable/logical-data-replication-overview) | ✗ | ✗ | | [FIPS-ready binary](/docs/stable/fips) | ✗ | ✗ | | Ingress private connectivity | ✓ | ✓ (provisioned storage only) | | [Egress private endpoints](/docs/cockroachcloud/egress-private-endpoints) | ✗ | ✓ (provisioned storage only) | | [Row-level security](/docs/stable/row-level-security) | ✓ | ✓ | | [Column-level encryption](/docs/stable/column-level-encryption) | ✓ | ✓ | | [CMEK](/docs/cockroachcloud/cmek) | ✗ | ✓ | | [Egress perimeter controls](/docs/cockroachcloud/egress-perimeter-controls) | ✗ | ✓ | ## Features on virtual clusters Virtual clusters inherit the host's license entitlements, but not every cluster feature applies to a virtual cluster. Refer to [feature availability on virtual clusters](/docs/continuum/virtual-clusters#feature-availability-on-virtual-clusters). ## Aegis availability [Cockroach Aegis](/docs/continuum/aegis-overview) is in private preview and requires sign-up and opt-in. It can monitor CockroachDB Cloud and self-hosted clusters, whether or not they use Continuum Cloud. Enrollment is separate from selecting a Continuum Cloud edition or add-on. For prerequisites and deployment requirements, see [How do I connect a cluster?](/docs/continuum/aegis-security-and-data-access#how-do-i-connect-a-cluster). # Get Started with Cockroach Continuum Cloud Source: https://docs.cockroachlabs.com/docs/continuum/get-started-with-continuum Cockroach Continuum Cloud work follows four stages: onboard data and build an application, scale it in production, monitor and optimize it, and integrate it with the rest of your ecosystem. This page walks through the path from a new organization to a production deployment, and where to go at each stage. ## Before you begin You need a Continuum Cloud organization, a running cluster, and a verified connection. If you are starting fresh, work through the [Quickstart with Cockroach Continuum Cloud](/docs/continuum/tutorial-quickstart) tutorial, which walks you through creating a Continuum Cloud organization, creating a cluster, connecting to it, and running your first queries. The rest of this page shows where to go at each stage of your Continuum Cloud work. ## Onboard data and build applications Bring an existing database to CockroachDB with the [Migration Assistant](/docs/continuum/migration-assistant-overview), which guides you through schema conversion, data load, and verification. To build an application, refer to [Develop and Connect](/docs/continuum/develop-and-connect-overview) for connections, transactions, and server-side logic. ## Scale production workloads [Deploy and manage](/docs/continuum/deploy-and-manage-overview) clusters across your environments. [Cockroach Plenum](/docs/continuum/plenum-overview) sizes and scales storage with your workload. To build AI features, refer to [Build AI Applications](/docs/continuum/build-ai-applications-overview). For performance work, refer to [Tune and Troubleshoot](/docs/continuum/tune-and-troubleshoot-overview), and for backups and replication, refer to [Disaster Recovery](/docs/continuum/disaster-recovery-overview). ## Monitor and optimize performance [Cockroach Aegis](/docs/continuum/aegis-overview) monitors your clusters and records findings and recommendations for you to review. To isolate and prioritize workloads on shared capacity, refer to [Manage Workloads](/docs/continuum/virtualization-overview). > [!NOTE] > > **This feature is in [private preview](/docs/releases/cockroachdb-feature-availability)** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. ## Integrate and govern your ecosystem [Secure and govern](/docs/continuum/secure-and-govern-overview) access to your organization and clusters. [Integrate](/docs/continuum/integrate-overview) with your ecosystem through changefeeds and Terraform. To understand what you pay for, refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). ## Next steps * Migrate an existing database with the [Migration Assistant](/docs/continuum/migration-assistant-overview). * Review your first [Aegis](/docs/continuum/aegis-overview) findings and recommendations. * Explore what each edition includes in [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). ## Demo video For a demonstration of how to get started with Continuum Cloud, watch the following video: [YouTube video player](https://www.youtube.com/embed/12A5C6njBMI) # Cockroach Continuum Cloud Docs Source: https://docs.cockroachlabs.com/docs/continuum/index Cockroach Continuum Cloud is the agentic database cloud built on CockroachDB. New here? Follow [Get Started with Cockroach Continuum Cloud](/docs/continuum/get-started-with-continuum). Find what you need by task below, or start with the [overview](/docs/continuum/overview). ## Onboard Data and Build Applications ### [Migrate Data](/docs/continuum/migration-assistant-overview) Move a database to CockroachDB with the Migration Assistant or the standalone MOLT tools. ### [Develop and Connect](/docs/continuum/develop-and-connect-overview) Connect your application and work with transactions, functions, stored procedures, and triggers. ## Scale Production Workloads ### [Deploy and Manage](/docs/continuum/deploy-and-manage-overview) Create clusters and manage them in the Console or through the Cloud API. ### [Size and Scale](/docs/continuum/plenum-overview) Understand how Cockroach Plenum sizes and scales clusters with your workload. ### [Build AI Applications](/docs/continuum/build-ai-applications-overview) Build AI features with vector search and connect agents through the CockroachDB Cloud MCP server. ### [Tune and Troubleshoot](/docs/continuum/tune-and-troubleshoot-overview) Diagnose and improve performance with best practices and recipes. ### [Survive Disasters](/docs/continuum/disaster-recovery-overview) Prepare for failures with managed backups and physical cluster replication. ## Monitor and Optimize Performance ### [Monitor and Optimize](/docs/continuum/aegis-overview) Review cluster health, workload reports, and Cockroach Aegis recommendations. ### [Manage Workloads](/docs/continuum/virtualization-overview) Isolate and prioritize workloads with virtual clusters, workspaces, and admission control. ## Integrate and Govern Your Ecosystem ### [Secure and Govern](/docs/continuum/secure-and-govern-overview) Control access and encrypt data with customer-managed keys. ### [Integrate](/docs/continuum/integrate-overview) Stream changes to external sinks and manage infrastructure with Terraform. ### [Manage Costs](/docs/continuum/editions-and-add-ons) Compare editions and add-ons, and manage pricing and billing. ## Explore by task # Integrate Overview Source: https://docs.cockroachlabs.com/docs/continuum/integrate-overview Cockroach Continuum Cloud clusters integrate with the rest of your stack the same way CockroachDB Cloud clusters do. Changefeeds stream row-level changes to external systems, and the Terraform provider manages resources as code. Changefeeds to external sinks are enabled by the [Data Sync add-on](/docs/continuum/editions-and-add-ons#add-ons), the one add-on available on Standard clusters. Sinkless changefeeds are outside the add-on boundary and work on every cluster. To monitor your clusters in third-party observability tools, you can also [export metrics](/docs/cockroachcloud/export-metrics). Pages in this section: * [Changefeed Sinks](/docs/stable/changefeed-sinks) * [Terraform Provider](/docs/cockroachcloud/provision-a-cluster-with-terraform) # Managed Backups Source: https://docs.cockroachlabs.com/docs/continuum/managed-backups # MCP Server Source: https://docs.cockroachlabs.com/docs/continuum/mcp-server # Deploy the Migration Assistant Source: https://docs.cockroachlabs.com/docs/continuum/migration-assistant-deploy > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). This page describes how to deploy and delete an instance of the [Migration Assistant](/docs/continuum/migration-assistant-overview) using the [Cloud Console](https://cockroachlabs.cloud) or the [Cloud API](/docs/cockroachcloud/cloud-api). At a high level, you take the following steps: 1. Create a Migration Assistant instance for an eligible target cluster using the Console or Cloud API. 2. Use the instance to migrate your data, as described in [Use the Migration Assistant](/docs/continuum/migration-assistant-use). 3. Delete the instance when the migration is complete. The Assistant does not create or configure the target database cluster. Use the [Cloud Console](https://cockroachlabs.cloud) or [ccloud CLI](#prepare-the-target-cluster-with-ccloud) to create or identify a target cluster that meets the [Migration Assistant eligibility requirements](/docs/continuum/migration-assistant-overview#eligibility), and configure its IP allowlist before you deploy the Assistant. ## Prerequisites * Your source database and target cluster meet the [Migration Assistant eligibility requirements](/docs/continuum/migration-assistant-overview#eligibility). * For Console deployment, your Cockroach Cloud account must have the [Cluster Admin](/docs/cockroachcloud/authorization#cluster-admin) role on the target cluster or the [Organization Admin](/docs/cockroachcloud/authorization#organization-admin) role in the organization. * For Cloud API deployment, install `ccloud` and log in to the organization that contains the target cluster. Refer to [Get Started with the ccloud CLI](/docs/cockroachcloud/ccloud-get-started). * For Cloud API deployment, create a Cloud API [service account and API key](/docs/cockroachcloud/managing-access). The service account must have the [Cluster Admin](/docs/cockroachcloud/authorization#cluster-admin) role on the target cluster or the [Organization Admin](/docs/cockroachcloud/authorization#organization-admin) role in the organization. The key inherits the roles of the service account. * Your PostgreSQL source database must be reachable over the network from CockroachDB Cloud. * Know the public IP address or network CIDR that will access the Assistant's web interface. ## Create an instance Create the instance in the Cloud Console or by calling the Cloud API. > [tab] Console > > 1. Log in to the [Cloud Console](https://cockroachlabs.cloud) and select the organization that contains the target cluster. > 2. On the target cluster's **Networking** page, [add your network to the IP allowlist](/docs/cockroachcloud/network-authorization#ip-allowlisting). > 3. In the left navigation, click **Migrations**, then click **New migration**. > 4. Select the **Target cluster**. The target must meet the [eligibility requirements](/docs/continuum/migration-assistant-overview#eligibility). > 5. Review the **Region**. For a single-region cluster, the region is preselected. For a multi-region cluster, select the region where the Assistant runs. You cannot change the region later; to move the Assistant, delete the instance and create it again. > 6. Click **Continue**. The instance appears with status **Deploying**. The page updates automatically; provisioning typically takes 10 to 20 minutes. > 7. When the status is **Ready**, continue to [Access the Assistant](#access-the-assistant). > > The **Status** column has the following values: > > | Status | Description | > | - | - | > | **Deploying** | The instance is provisioning. | > | **Ready** | The instance is running and responding. **Open assistant** is available from the **Actions** menu. | > | **Unavailable** | The instance is running but not responding. The page keeps checking and updates the status when the instance responds. | > | **Unknown** | The instance is running, but its health could not be checked. The page keeps checking and updates the status. | > | **Failed** | Provisioning failed. The error appears below the status. After addressing its cause, click **Retry deploy**, which creates the instance again in the same region. | > | **Deleting** | The instance is being torn down after a delete request. | > [tab] Cloud API > > ### Prepare the target cluster with ccloud > > Use `ccloud` to prepare the target cluster. For complete command syntax and options, refer to the [ccloud CLI Command Reference](/docs/cockroachcloud/ccloud-reference). > > 1. Log in to the organization that contains the target cluster: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ccloud auth login --org {organization-label} > ``` > > 2. List the clusters in the organization: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ccloud cluster list > ``` > > The output includes each cluster's name, ID, plan, and state. Select an existing eligible target and record both its name and ID. `ccloud` commands identify the cluster by name; the Migration Assistant API identifies it by ID. > > If you need to create an Advanced target cluster, use `ccloud cluster create`. Replace the placeholders with a supported cloud, region, node count, and cluster size: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ccloud cluster create ADVANCED {cluster-name} {region}:{node-count} \ > --cloud {cloud-provider} \ > --vcpus {vcpus-per-node} \ > --storage-gib {storage-gib-per-node} > ``` > > For additional creation options, refer to [Create a new cluster with ccloud](/docs/cockroachcloud/ccloud-reference#create-a-new-cluster). > > 3. Add the network that will access the Assistant to the target cluster's IP allowlist. For a single public IP address, use a `/32` CIDR: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ccloud cluster networking allowlist create {cluster-name} {ip-address}/32 \ > --name migration-assistant-access \ > --sql \ > --ui > ``` > > 4. Verify the allowlist entry: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ccloud cluster networking allowlist list {cluster-name} > ``` > > For details, refer to [Create and manage IP allowlists with ccloud](/docs/cockroachcloud/ccloud-reference#create-and-manage-ip-allowlists). > > `ccloud` does not currently expose the Migration Assistant endpoint. Use the target cluster ID from `ccloud cluster list` with the Cloud API in the following steps. > > ### Create a Migration Assistant instance > > To manage the instance, use the cluster's `migration-assistant` endpoint in the Cloud API. In the following examples, replace `{cluster_id}` with the cluster ID returned by `ccloud cluster list`, and replace `{secret_key}` with the API key of your service account. > > 1. Create the instance: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > curl --request POST \ > --url 'https://cockroachlabs.cloud/api/v1/clusters/{cluster_id}/migration-assistant' \ > --header 'Authorization: Bearer {secret_key}' \ > --header 'Content-Type: application/json' \ > --data '{}' > ``` > > The optional `region` field specifies the Assistant's deployment region. If omitted, the service selects a default region. > > The call returns immediately with status `PENDING` while the control plane provisions the instance in the background: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "id": "f83ef76b-0e72-4a40-bbcf-a3d6188726f5", > "cluster_id": "c061d097-84b3-4d49-b280-2f579e4a18cb", > "deployed_region": "us-east1", > "status": "PENDING", > "url": "", > "last_error": "", > "created_at": "2026-08-07T17:37:31.235157Z", > "updated_at": "2026-08-07T17:37:31.235157Z", > "username": "", > "password": "", > "bucket_grantee": "", > "health": "NOT_COMPUTED" > } > ``` > > 2. Poll the same endpoint every 60 seconds until the status is `RUNNING`. Provisioning typically takes 10 to 20 minutes, because it creates a dedicated node pool and boots the Assistant. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > curl --request GET \ > --url 'https://cockroachlabs.cloud/api/v1/clusters/{cluster_id}/migration-assistant' \ > --header 'Authorization: Bearer {secret_key}' > ``` > > When provisioning completes, the response includes the URL for the Assistant's web interface. The Assistant uses Cockroach Cloud single sign-on (SSO), so the `username` and `password` fields are empty: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "id": "f83ef76b-0e72-4a40-bbcf-a3d6188726f5", > "cluster_id": "c061d097-84b3-4d49-b280-2f579e4a18cb", > "deployed_region": "us-east1", > "status": "RUNNING", > "url": "https://molt-ai.{generated_id}.crdb.io/", > "last_error": "", > "created_at": "2026-08-07T17:37:31.235157Z", > "updated_at": "2026-08-07T17:40:26.406841Z", > "username": "", > "password": "", > "bucket_grantee": "{bucket_grantee}", > "health": "HEALTHY" > } > ``` > > The `url` contains a generated hostname in the `molt-ai` subdomain, such as `https://molt-ai.bpnk.crdb.io/`. > > `bucket_grantee` identifies the cloud identity to grant access to your bucket when using optional cloud-storage loading. At launch, this option supports Google Cloud Storage only, and both the target cluster and bucket must be on Google Cloud. > > 3. Record the `url` from the `RUNNING` response. > > The status field has the following values: > > | Status | Description | > | - | - | > | `PENDING` | The instance is provisioning. The `url` is empty. | > | `RUNNING` | The instance is ready. The response includes the `url` for the Assistant's web interface. | > | `FAILED` | Provisioning failed. The `last_error` field reports the cause. To retry, send the create request again. The instance is retried in place in the same region. To change the region, [delete the instance](#delete-the-instance) and create it again. | > | `DELETING` | The instance is being torn down after a delete request. | Each instance is dedicated to your migration. It runs on isolated capacity alongside your cluster, with its own TLS certificate, and is separate from the infrastructure running the cluster itself. ## Access the Assistant 1. In the Console, go to **Migrations**. For the target cluster with status **Ready**, open the **Actions** menu and select **Open assistant**. The Assistant opens in a new tab. If you use the Cloud API, open the `url` from the `RUNNING` response in a browser. 2. Sign in with your Cockroach Cloud account. You must be a member of the target cluster's organization. The Assistant instance serves only your migration, and is reachable only from networks on the cluster's IP allowlist. If the URL times out, verify that the allowlist contains your network's current public IP address [in the Console under **Networking**](/docs/cockroachcloud/network-authorization#ip-allowlisting), or use `ccloud cluster networking allowlist list {cluster-name}`. If necessary, add or update the network in the Console or as described in [Prepare the target cluster with ccloud](#prepare-the-target-cluster-with-ccloud). After you add or update an allowlist entry, the change can take a few minutes to propagate to the Assistant. ## Connect your source and target In the Assistant, connect your source database and run the connectivity check before starting the migration stages. Refer to [Use the Migration Assistant](/docs/continuum/migration-assistant-use). Because the Assistant runs in CockroachDB Cloud, your source database must be reachable from CockroachDB Cloud, not only from your workstation: * The source needs a routable endpoint: a public hostname or IP address, or a private connection path. A database bound to localhost, or reachable only over your VPN, does not work. * Your network and firewall rules must allow inbound connections from the Assistant on the database port. * The connection credentials must be able to read the source's schema catalog and [`SELECT`](/docs/stable/select-clause) the data to migrate. ## Delete the instance When your migration is complete: > [tab] Console > > 1. Download any converted DDL, scripts, or reports you want to keep. > 2. In the Console, go to **Migrations**. For the target cluster, open the **Actions** menu and select **Delete migration**. > 3. In the confirmation dialog, click **Delete**. The row shows **Deleting** until the instance is removed. > > Deleting the Assistant stops any migration in progress and releases its dedicated compute. Deletion is available once deployment completes or fails. > [tab] Cloud API > > 1. Download any converted DDL, scripts, or reports you want to keep. > 2. Delete the Assistant instance: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > curl --request DELETE \ > --url 'https://cockroachlabs.cloud/api/v1/clusters/{cluster_id}/migration-assistant' \ > --header 'Authorization: Bearer {secret_key}' > ``` > > The response shows `DELETING` while teardown is in progress: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "id": "f83ef76b-0e72-4a40-bbcf-a3d6188726f5", > "cluster_id": "c061d097-84b3-4d49-b280-2f579e4a18cb", > "deployed_region": "us-east1", > "status": "DELETING", > "url": "", > "last_error": "", > "created_at": "2026-08-07T17:37:31.235157Z", > "updated_at": "2026-08-07T17:58:08.947081Z", > "username": "", > "password": "", > "bucket_grantee": "", > "health": "NOT_COMPUTED" > } > ``` > > When teardown completes, the endpoint reports that no Assistant exists for the cluster: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "code": 5, > "message": "migration assistant does not exist for this cluster", > "details": [] > } > ``` ## See also * [Migration Assistant Overview](/docs/continuum/migration-assistant-overview) * [Use the Migration Assistant](/docs/continuum/migration-assistant-use) # Migration Assistant Overview Source: https://docs.cockroachlabs.com/docs/continuum/migration-assistant-overview > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). Moving data from an existing database is often the largest step in adopting a new platform. Migration Assistant is [Cockroach Continuum Cloud](/docs/continuum/overview)'s AI-guided workflow for moving from an existing PostgreSQL database onto CockroachDB: it guides you through connecting a source database, converting its schema, loading and verifying data, and planning your next steps. The Assistant explains its work and lets you review and edit generated statements before you apply them. This page explains what the Migration Assistant is and how it works at a high level. For instructions on deploying it, refer to [Deploy the Migration Assistant](/docs/continuum/migration-assistant-deploy). For instructions on using it to move your data, refer to [Use the Migration Assistant](/docs/continuum/migration-assistant-use). ## Eligibility The Migration Assistant is available in open preview, with no organization enrollment required. Your source database and target cluster must meet the following requirements: * The source database runs PostgreSQL 15 to 18. * The target is an existing, single-region [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster in a Continuum Cloud organization or an existing, single-region [CockroachDB Advanced](/docs/cockroachcloud/plan-your-cluster-advanced) cluster in another CockroachDB Cloud organization. * The target cluster does not already have a Migration Assistant instance. Each target cluster can have one instance at a time. [CockroachDB Basic](/docs/cockroachcloud/plan-your-cluster-basic), [CockroachDB Standard](/docs/cockroachcloud/plan-your-cluster), BYOC ([Continuum Cloud](/docs/continuum/byoc-overview) or [CockroachDB Cloud](/docs/cockroachcloud/byoc-overview)), CockroachDB self-hosted, and multi-region target clusters are not supported in the Migration Assistant preview. Azure target clusters are not currently supported. ## PostgreSQL compatibility Support for a PostgreSQL source version does not mean that every feature used by the source database can be migrated automatically. Review the converted schema and migration plan for unsupported objects and changes that affect application behavior. The Migration Assistant reports which objects cannot be converted and require manual work. The following limitations apply during preview: | Source feature | Migration behavior and required action | | - | - | | Users, roles, privileges, and ownership | The Assistant does not migrate users, roles, role memberships, grants, default privileges, or object ownership. Newly created objects are owned by the target connection user. Re-create the required users and roles, then apply the appropriate ownership and privileges on the target. Per-role and per-database default settings also require manual configuration. | | Row-level security (RLS) | The Assistant does not migrate policies or the settings that enable or force RLS. Newly created tables have RLS disabled and no policies. Re-create the policies and enable the required RLS settings before allowing application access. Refer to [Row-Level Security](/docs/stable/row-level-security). | | Triggers | Supported PL/pgSQL trigger functions can migrate through the routine workflow, but the Assistant does not create the trigger objects that invoke them. Review the skipped triggers and manually re-create those supported by the target after their functions are installed. Refer to [CREATE TRIGGER](/docs/stable/create-trigger). | | Features that depend on the target version | A converted statement can require a newer CockroachDB version than the target cluster runs. Check feature availability in the documentation for your target version and test the generated SQL before relying on it. Successful conversion alone does not establish target-version compatibility. | For broader differences between PostgreSQL and CockroachDB, refer to [PostgreSQL Compatibility](/docs/stable/postgresql-compatibility). CockroachDB support for a feature does not by itself mean that the Migration Assistant migrates it automatically. ## How it works You [deploy the Migration Assistant to CockroachDB Cloud](/docs/continuum/migration-assistant-deploy) using the Console or Cloud API. There is nothing to install locally. The Assistant uses the [MOLT (Migrate Off Legacy Technology) toolset](/docs/molt/migration-overview) for conversion, data load, and verification. You can download converted DDL and generated scripts. During the migration, you can ask the **Migration agent** questions about your schema and the conversion in a chat panel. The Migration agent may suggest updates to your schema, stored procedures, and user-defined functions, which you can choose whether to apply. For more information, refer to [Ask questions in the Migration agent panel](/docs/continuum/migration-assistant-use#ask-questions-in-the-migration-agent-panel). ## Migration sequence The Assistant guides you through the following migration sequence. 1. **Connect and verify.** In this step the Assistant connects to the source database and verifies read permissions. It also connects to the target database and verifies write permissions. 2. **Select what to migrate.** The Assistant discovers the source schema, and you select the objects to migrate. 3. **Convert the schema.** The Assistant converts the source schema to CockroachDB DDL, explains each change it makes, and calls out anything that needs your decision. You can edit any statement before applying it. 4. **Generate the plan.** The Assistant assesses the selected objects and schema-conversion decisions, then produces an ordered migration plan. 5. **Complete pre-migration work.** You review and complete the executable and manual steps required to prepare the target for loading data. 6. **Load data.** The Assistant moves the source data into the target cluster, using [MOLT Fetch](/docs/molt/molt-fetch). 7. **Convert and test routines.** The Assistant classifies and converts source [stored procedures](/docs/continuum/stored-procedures) and [user-defined functions (UDFs)](/docs/continuum/user-defined-functions), and generates tests for your review. 8. **Complete post-migration work.** You restore deferred database objects including indexes and foreign keys, and verify loaded data with [MOLT Verify](/docs/molt/molt-verify). Later, outside the Migration Assistant, you will test the application against the target. 9. **Review results.** The Assistant summarizes the migration, identifies objects that still require manual work, and recommends next steps. For more information about the migration sequence, refer to [Use the Migration Assistant](/docs/continuum/migration-assistant-use). > [!NOTE] > > The Assistant does not run ongoing replication or perform application cutover. Its scope ends at a converted, loaded, and verified target. For ongoing replication, refer to [MOLT Replicator](/docs/molt/molt-replicator). For application validation and cutover preparation, refer to [Migration Best Practices](/docs/molt/migration-strategy). ## What is shared with the Migration agent The **Migration agent** is the AI component of the Migration Assistant. Cockroach Labs manages the Migration agent in its own cloud account, so you do not need to configure or connect a separate AI service. Your database credentials stay with the Migration Assistant and are never shared with the Migration agent. To analyze compatibility and generate a migration plan, the Assistant shares the following information with the Migration agent: * Schema structure and definitions, including object DDL for tables, views, types, and routines. * Limited table statistics, such as row counts, that help determine how to group tables in [MOLT Fetch](/docs/molt/molt-fetch) commands. * Text that you enter in the **Migration agent** panel. The Assistant tokenizes schema identifiers by default. Tokenization obfuscates names by replacing database, schema, table, column, type, routine, and routine-variable names with generated identifiers before schema content is shared with the Migration agent. The **Tokenization** tab previews what will be shared and lets you inspect the generated mappings. Database row data is **never** shared with the Migration agent. It moves only between the source database, target database, and customer-controlled storage. ## Demo video For a demonstration of how to use the Migration Assistant, watch the following video: [YouTube video player](https://www.youtube.com/embed/O7wiXpMgx24) ## See also * [Deploy the Migration Assistant](/docs/continuum/migration-assistant-deploy) * [Use the Migration Assistant](/docs/continuum/migration-assistant-use) # Use the Migration Assistant Source: https://docs.cockroachlabs.com/docs/continuum/migration-assistant-use > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). This page has instructions for using the Migration Assistant to move data from an existing PostgreSQL database onto CockroachDB. The steps on this page follow the [migration sequence](/docs/continuum/migration-assistant-overview#migration-sequence): they guide you through connecting a source database, converting its schema, loading and verifying data in the target database, and identifying the work that remains before cutover. Along the way, the Assistant explains its work and lets you review and edit generated statements before you apply them. It guides the migration, but you remain responsible for reviewing generated SQL and Migration agent suggestions, testing application behavior, and planning replication and cutover. You can ask questions in the **Migration agent** panel throughout the workflow. For more general information about the Migration Assistant, see the [Migration Assistant Overview](/docs/continuum/migration-assistant-overview). > [!WARNING] > > Generated commands and downloaded scripts can contain database connection strings and credentials. Store them securely, and do not copy them into tickets, chat, or public logs. ## Prerequisites * Complete the instructions in [Deploy the Migration Assistant](/docs/continuum/migration-assistant-deploy), including target cluster setup. * Have a connection string for a source database that meets the [Migration Assistant eligibility requirements](/docs/continuum/migration-assistant-overview#eligibility). The database must be running and reachable from CockroachDB Cloud, and the connection user must be able to read the schema catalog and [`SELECT`](/docs/stable/select-clause) data. ## Step 1. Connect and verify When you first open the Assistant page, the target connection is prefilled with the CockroachDB cluster where you [deployed the Assistant](/docs/continuum/migration-assistant-deploy). 1. Review the data-handling notice on the **Connect & verify** page. 2. Enter the connection string for your source database. The source must be reachable from CockroachDB Cloud. 3. Verify that the prefilled target connection identifies the cluster where you deployed the Assistant. 4. Click **Validate connections**. The Assistant checks source connectivity, authentication, [`SELECT`](/docs/stable/select-clause) access, and version compatibility. It checks target connectivity, authentication, schema-changing privileges, and cluster health. 5. If a check fails, correct the connection details or network access and validate again. Continue only after both databases report that they are ready. ![Migration Assistant Connect and verify page showing the source connection action, prefilled target connection, and validation checks](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-connect-and-verify.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=fafde87417a0605cc5a0198f80e108f4) ## Step 2. Select objects The Assistant discovers the source's tables and routines. 1. On the **Tables** and **Routines** tabs, select the objects to migrate. You can search and filter the discovered objects. 2. Review objects that the Assistant reports as already existing on the target. 3. Review the tokenization settings. Tokenization obfuscates the names of schema objects before schema content is shared with the Migration agent. For details, refer to [What is shared with the Migration agent](/docs/continuum/migration-assistant-overview#what-is-shared-with-the-migration-agent). 4. Click **Save selection**, and then continue to schema conversion. > [!TIP] > > You can migrate a subset of the source's schemas or databases per run. To migrate a large source, split it into several migrations and run them sequentially. ![Migration Assistant Select objects page showing selected tables grouped by schema](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-select-objects.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=f9b01edaef9f37863e6116bfe3f09af5) ## Step 3. Convert and review the schema The Assistant converts the selected source schema to CockroachDB DDL. It separates statements that could not be converted from statements that contain valid but lossy substitutions. 1. Review the conversion summary, including every unconverted statement and lossy substitution. 2. Compare the source and target data definition language (DDL). Edit the target DDL when necessary, or download the converted DDL for offline review. 3. For an unconverted statement, click **Ask AI to convert these** to request a conversion and an explanation of its behavioral differences. 4. For grouped substitutions, click **Ask AI about these** to request an explanation of the changes and their application impact. 5. Apply a Migration agent suggestion only after confirming that its target DDL and data semantics are appropriate for your workload. 6. Continue after you have reviewed each conversion failure and lossy substitution and accounted for any required follow-up work. ![Schema conversion page showing an unconverted statement, lossy substitutions, and source and target DDL](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-schema-conversion.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=3465b1d50aed54d596d7925068b3459c) ![Migration agent panel explaining how to convert an unsupported PostgreSQL money column to CockroachDB DDL](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-schema-conversion-ai.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=2233289bdf057ee95c47f18482b0d398) > [!NOTE] > > Executable DDL is not necessarily behaviorally equivalent to the source schema. Review application behavior, constraints, and data modeling for every lossy substitution. ## Step 4. Generate and review the migration plan The Assistant assesses the selected objects and your schema-conversion decisions, then generates an ordered migration plan. 1. Review the compatibility rating and the counts of pre-migration steps, table migrations, routine conversions, and post-migration steps. 2. Review the listed issues and warnings, and make note of any that will require a follow-up action. 3. Review warnings and plan notes, including the data-load mode, type conversions, foreign-key handling, source statistics, network and TLS requirements, and routines that require individual review. ## Step 5. Complete pre-migration steps The plan can contain required, optional, executable, and manual steps. 1. Review the entire list and expand each step to inspect its command or instructions. 2. For an executable step, review the generated command and click **Execute**. 3. Perform manual steps outside the Assistant. 4. Click **Skip** only when an optional step does not apply, or you have satisfied the prerequisite elsewhere. 5. Confirm that all required pre-migration steps are complete before continuing. Pre-migration work can include creating the target database and schemas, applying converted table DDL, gathering source statistics, and generating a type-map file for edited column types. ![Pre-migration page showing required executable steps and an optional manual source-database step](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-pre-migration.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=0129386a093e05420980b5390da0271d) ## Step 6. Load data The Assistant generates and runs [MOLT Fetch](/docs/molt/molt-fetch) commands to move the selected data to the target cluster. 1. Review the generated scripts and the plan's data-load mode before execution. 2. Click **Execute** for each table-migration batch and monitor the live MOLT output. 3. If a batch fails, review its output and the displayed recovery instructions before retrying it. 4. Confirm that every selected table has migrated before continuing. Direct-copy batches require network connectivity from the Assistant to both databases and cannot resume in the middle of a batch. ![Data load page showing three completed direct-copy table-migration batches](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-data-load.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=39ba905f3829d02023b69cc2c7029fe0) ## Step 7. Review, create, and test routines The Assistant classifies stored procedures and user-defined functions as direct copy, minor fix, assisted rewrite, or manual rewrite. 1. Review the classification, converted SQL, explanation, confidence, and risk factors for every routine. 2. Click **Create all** for direct-copy and minor-fix routines. Assisted and manual rewrites require individual decisions. 3. For an assisted rewrite, compare the source and converted SQL, edit the proposed SQL if necessary, and acknowledge its risks before creating it. 4. Review the generated tests before running them. Source execution requires explicit consent; otherwise, the Assistant tests only the target. 5. Compare source and target results when source testing is enabled. 6. Rewrite unsupported routines outside the Assistant, or skip them and record the required follow-up work. If the source uses triggers, migrating their functions does not create the triggers themselves. After installing the functions, manually re-create the triggers supported by your target and test their behavior. Refer to [PostgreSQL compatibility](/docs/continuum/migration-assistant-overview#postgresql-compatibility). ![Routine review page showing direct-copy, minor-fix, assisted-rewrite, and manual-rewrite classifications](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-routine-review.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=6606d3fdbb5addf42774bc6a8bbb7010) ![Routine review showing source and converted SQL, generated test queries, and controls for source and target testing](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-routine-testing.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=a26dfbbc666631ac05da7b04d00e2705) > [!NOTE] > > A successful target-only test does not establish source and target behavioral equivalence. Review generated tests carefully, and test migrated application behavior separately. ## Step 8. Complete post-migration work Post-migration steps restore database objects omitted for load performance and verify the migrated data. 1. Review every required and optional post-migration step. 2. After all data loads finish, execute the steps that recreate secondary indexes and deferred foreign keys. 3. Run [MOLT Verify](/docs/molt/molt-verify) for every migrated schema and review the output for row-count or data mismatches. 4. Before application testing or cutover, manually configure the required users, roles, ownership, privileges, and row-level security on the target. The Assistant does not migrate this configuration; refer to [PostgreSQL compatibility](/docs/continuum/migration-assistant-overview#postgresql-compatibility). 5. Run basic application tests against the target using the application's database user, including checks of its access permissions. > [!NOTE] > > For a low-downtime migration, configure ongoing replication with [MOLT Replicator](/docs/molt/molt-replicator) and plan the application cutover separately. The Migration Assistant does not run ongoing replication or perform application cutover. ![Post-migration page showing index creation, deferred foreign keys, data verification, and manual application testing](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-post-migration.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=9900bb4a05993e105ad0218de156cfb9) ## Step 9. Review results and plan next steps The **Results** page can mark the guided migration complete while still listing skipped or failed objects that require manual work. 1. Review the migration totals, source and target versions, duration, throughput, load mode, and verification status. 2. Review the source-execution audit and any high-risk acknowledgements. 3. Use **Objects not migrated** as the required work queue. Resolve each skipped or failed object. 4. Test application behavior affected by type substitutions or routine rewrites. 5. [Test and optimize application queries](/docs/molt/migration-strategy#test-query-results-and-performance) and [rehearse the production cutover](/docs/molt/migration-strategy#perform-a-dry-run). ![Migration results showing migrated tables and routines, verification status, source-execution audit, and an object requiring manual intervention](https://mintcdn.com/cockroachlabs/6hk9GcuTSZOzgBDT/images/continuum/migration-assistant-results.jpg?fit=max\&auto=format\&n=6hk9GcuTSZOzgBDT\&q=85\&s=0d0915e9410ab438f726ea5a8074bf40) For a low-downtime migration, configure ongoing replication with [MOLT Replicator](/docs/molt/molt-replicator) and plan the application cutover separately. The Assistant does not run ongoing replication or perform application cutover. ## Ask questions in the Migration agent panel Throughout the migration, you can ask the Assistant questions about your schema, conversion issues, and generated plan in the **Migration agent** panel. The panel groups the interaction history by migration stage. Treat its suggestions as proposals and review them before applying changes. ## Results and downloads The Assistant records migration activity and your acknowledgements of consequential actions. The **Results** page includes source-execution and high-risk acknowledgement information. You can also download converted DDL from schema conversion and generated [MOLT Fetch](/docs/molt/molt-fetch) scripts from data load for offline review. ## See also * [Delete the Migration Assistant instance](/docs/continuum/migration-assistant-deploy#delete-the-instance) * [Configure MOLT Replicator for ongoing replication](/docs/molt/molt-replicator) # MOLT Toolset Source: https://docs.cockroachlabs.com/docs/continuum/molt-toolset # Continuum Cloud Overview Source: https://docs.cockroachlabs.com/docs/continuum/overview Cockroach Continuum Cloud is the *agentic database cloud* built on CockroachDB. Continuum Cloud provisions and operates databases for applications and AI agents, and includes AI agents that help operate the databases themselves. Continuum Cloud combines CockroachDB's [distributed SQL engine](/docs/v26.3/architecture/overview) with virtualization, elastic storage, managed agents, and usage-based economics. ## Databases for agentic workloads Agents create applications. Because each application needs persistent state, this quickly multiplies the number of databases an organization will run. Agents work continuously and issue many requests in parallel, so traffic patterns include frequent spikes. Provisioning a dedicated cluster for each database does not scale to agentic workloads. Because each cluster is typically overprovisioned for its peak workload, most capacity sits idle, and each new cluster adds operational burden. Continuum Cloud addresses this problem in five ways: * [Virtualization](/docs/continuum/virtualization-overview) runs many isolated databases as virtual clusters on a host cluster, on capacity provisioned once, without a dedicated cluster for each database. * [Cockroach Plenum](/docs/continuum/plenum-overview) separates storage from compute, so that each scales independently with demand. * [Cockroach Aegis](/docs/continuum/aegis-overview) monitors your clusters continuously and generates recommendations based on what it observes. * [Migration Assistant](/docs/continuum/migration-assistant-overview) uses AI to analyze, convert, and load data from your source database into a Continuum Cloud cluster, as you review each step in the migration. * [Editions and add-ons](/docs/continuum/editions-and-add-ons) bill for usage: usage-based storage is billed on data stored, and add-ons are billed only while active. ### Terminology * **Organization:** The boundary of Continuum Cloud. New CockroachDB Cloud organizations use Continuum Cloud, and all clusters, workspaces, and billing in an organization belong to it. For how access is managed within an organization, refer to [Authorization](/docs/cockroachcloud/authorization). * **Cluster:** The unit you create and manage on Continuum Cloud. Every cluster is a CockroachDB cluster, in one of three roles: standalone, host, or virtual. For the underlying architecture, refer to the [CockroachDB architecture overview](/docs/stable/architecture/overview). * **Host cluster:** A [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster created with virtualization enabled. It runs its own CockroachDB nodes and provides the capacity that virtual clusters share. Refer to [Host Clusters and Workspaces](/docs/continuum/workspaces). * **Virtual cluster:** An isolated database created on a host cluster and served by the host's nodes, with no separate charge. Continuum virtual clusters are distinct from self-hosted cluster virtualization, which shares the underlying architecture but has a different management surface. Refer to [Continuum Virtualization](/docs/continuum/virtualization-overview) and [Virtual Clusters](/docs/continuum/virtual-clusters) for more information. * **Workspace:** A logical grouping that associates virtual clusters with a host cluster. Each host cluster has a single default workspace. All virtual clusters are created in this default workspace and inherits the default burst limit. Refer to [Workspaces and Host Clusters](/docs/continuum/workspaces). * **Edition:** A cluster plan that sets infrastructure, availability, and feature boundaries. Continuum Cloud offers Standard and Mission Critical. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). * **Shared and dedicated infrastructure:** The two kinds of infrastructure clusters run on. Shared infrastructure serves clusters from multiple organizations; dedicated infrastructure is provisioned for a single cluster. Standard runs on shared infrastructure, and Mission Critical runs on dedicated infrastructure. * **Add-on:** A capability that a cluster uses and is billed for only while it is active, such as hosting virtual clusters or running changefeeds to a sink. Refer to [Add-ons](/docs/continuum/editions-and-add-ons#add-ons). * **Storage model:** The choice, made at cluster creation, between usage-based storage, backed by [Plenum](/docs/continuum/plenum-overview) and billed on data stored, and provisioned storage, billed on provisioned capacity. ### CockroachDB Every cluster on Continuum Cloud is a CockroachDB cluster. Standalone and host clusters run their own CockroachDB nodes, and a virtual cluster is a CockroachDB virtual cluster served by its host's nodes. In all cases, the CockroachDB documentation, beginning with the [architecture overview](/docs/v26.3/architecture/overview), applies to SQL, transactions, and database behavior. Direct entry points into the CockroachDB documentation appear in the CockroachDB section of this documentation set. These components rely on CockroachDB's core capabilities: distributed transactions with [strong consistency](/docs/v26.3/architecture/overview), [multi-region deployment](/docs/v26.3/multiregion-overview), fault tolerance, and [horizontal scale](/docs/v26.3/architecture/glossary). Continuum adds the platform layer on top of CockroachDB: how clusters are created, shared, stored, operated, and billed. ### Virtualization With virtualization, a host cluster is provisioned once and divided among many isolated virtual clusters, each with its own connection string, users, schemas, and backups. Virtualization is available only on Continuum. Refer to [Virtualization Overview](/docs/continuum/virtualization-overview). ### Plenum Plenum is the storage layer behind Continuum Cloud's usage-based storage model. Clusters that use it bill for data stored rather than capacity provisioned. Refer to [Plenum Overview](/docs/continuum/plenum-overview). ### Aegis Aegis is CockroachDB's managed agent. It monitors your clusters continuously and records findings and recommendations for you to review. Aegis operates read-only. Refer to [Aegis Overview](/docs/continuum/aegis-overview). ### Migration Assistant Migration Assistant is an AI-guided workflow for migrating a database to CockroachDB, from schema conversion through data load and verification. Refer to [Migration Assistant Overview](/docs/continuum/migration-assistant-overview). ### Editions and add-ons Continuum Cloud offers clusters in two editions, Standard and Mission Critical, with add-ons that enable additional capabilities and bill only while in use. Refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). ## Continuum Cloud and CockroachDB Cloud Continuum Cloud runs on CockroachDB Cloud. Continuum Cloud is enabled per [organization](/docs/cockroachcloud/authorization#overview-of-the-cockroachdb-cloud-authorization-model). New CockroachDB Cloud organizations use Continuum Cloud, and the same user can belong to Continuum Cloud and other Cloud organizations. Existing clusters continue to run in their existing Cloud configurations and are not automatically migrated to Continuum Cloud. ## Feature availability | Component | Availability | | - | - | | Editions and add-ons | Available on Continuum Cloud organizations | | [Bring Your Own Cloud (BYOC)](/docs/continuum/byoc-overview) | Available on request for Continuum Cloud organizations billed by invoice | | Virtualization (hosts, workspaces, virtual clusters) | [Preview](/docs/continuum/feature-availability) | | Plenum (usage-based storage) | [Preview](/docs/continuum/feature-availability) | | Aegis | [Private preview](/docs/continuum/feature-availability) | | Migration Assistant | [Preview](/docs/continuum/feature-availability) | # Performance Best Practices Source: https://docs.cockroachlabs.com/docs/continuum/performance-best-practices # Performance Recipes Source: https://docs.cockroachlabs.com/docs/continuum/performance-recipes # Physical Cluster Replication Source: https://docs.cockroachlabs.com/docs/continuum/physical-cluster-replication # Cockroach Plenum Overview Source: https://docs.cockroachlabs.com/docs/continuum/plenum-overview > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). Cockroach Plenum is Cockroach Continuum Cloud's elastic storage layer that separates a cluster's storage from its compute. Plenum provides a custom storage architecture purpose-built for CockroachDB that preserves CockroachDB's existing [replication and consensus behavior](/docs/stable/architecture/replication-layer) while removing reliance on a provisioned disk layer. On Continuum Cloud, Plenum backs the [*usage-based* storage model](#usage-based-storage), available on eligible [Mission Critical](/docs/continuum/editions-and-add-ons#editions) clusters. Usage-based storage is billed based on physical-used GiB rather than provisioned capacity. ## How it works CockroachDB nodes write to Plenum through the [storage layer](/docs/stable/architecture/storage-layer) instead of writing to attached disks. Plenum manages the physical placement and redundancy of stored data across availability zones. Above the storage-layer boundary, [SQL](/docs/stable/architecture/sql-layer), [transaction](/docs/stable/architecture/transaction-layer), and [replication](/docs/stable/architecture/replication-layer) behavior remains unchanged. ## Compared to provisioned storage With provisioned block storage, each node has its own attached volume, so storage and compute are sized and scaled together as a unit. You provision capacity for the data you expect, pay for it whether or not it is full, and resize it as data grows. Provisioned block-storage services such as Amazon EBS also replicate data internally, adding cost and redundancy on top of CockroachDB's [replication](/docs/stable/architecture/replication-layer). Plenum removes the provisioned-disk layer entirely. CockroachDB nodes write to a shared storage service instead of to attached disks, and storage is billed based on physical-used GiB. ## Usage-based storage When you [create a Mission Critical cluster](/docs/continuum/create-a-cluster), you choose its storage model: * *Usage-based.* Storage is backed by Plenum. You do not provision storage capacity or bandwidth. Storage capacity scales automatically as data is added or removed. You are billed based on physical-used GiB, and the Console shows storage consumption rather than provisioned capacity. * *Provisioned.* Storage is backed by conventional block volumes and billed as provisioned capacity. Usage-based storage is available on single-region Mission Critical clusters running CockroachDB v26.3 or later. Multi-region Mission Critical clusters and host clusters use provisioned storage. Plenum is initially available in the following AWS regions: * `us-east-1` * `us-west-2` * `eu-central-1` * `eu-west-1` Standard clusters run on shared infrastructure with usage-based storage billing, separate from Plenum. The storage model is chosen when you [create the cluster](/docs/continuum/create-a-cluster), and cannot be changed. To change storage models, create a new cluster and move the workload. For details on how storage is billed, refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). ## Independent scaling Because the nodes running CockroachDB are stateless and separated from the storage layer, storage now scales independently. ## Durability and security Plenum provides redundant storage across availability zones in a region. Data is encrypted at rest with its own keys, so clusters sharing Plenum's storage service are cryptographically isolated from one another. ## Demo video For a demonstration of how to use Cockroach Plenum and cluster virtualization, watch the following video: [YouTube video player](https://www.youtube.com/embed/NSfGxRn_koE) ## See also * [Editions and Add-Ons](/docs/continuum/editions-and-add-ons) * [Create a Cluster](/docs/continuum/create-a-cluster) * [Mission Critical clusters](/docs/continuum/editions-and-add-ons#editions) # Pricing Source: https://docs.cockroachlabs.com/docs/continuum/pricing # Secure and Govern Overview Source: https://docs.cockroachlabs.com/docs/continuum/secure-and-govern-overview Access to Cockroach Continuum Cloud is governed at the organization level, and clusters inherit CockroachDB Cloud's security model. Mission Critical clusters add customer-managed encryption keys and egress controls. Security feature availability differs by edition and is enforced by the database's license entitlements. For the boundaries, refer to [Feature Reference](/docs/continuum/feature-reference) and [Editions and Add-Ons](/docs/continuum/editions-and-add-ons#feature-entitlements-and-license-behavior). The [Advanced Compliance add-on](/docs/continuum/editions-and-add-ons#add-ons) applies at the organization level, across the organization's Mission Critical clusters, and grants access to the Trust Center. Pages in this section: * [Authorization](/docs/cockroachcloud/authorization) * [CMEK](/docs/cockroachcloud/cmek) # Stored Procedures Source: https://docs.cockroachlabs.com/docs/continuum/stored-procedures # Terraform Provider Source: https://docs.cockroachlabs.com/docs/continuum/terraform-provider # Triggers Source: https://docs.cockroachlabs.com/docs/continuum/triggers # Tune and Troubleshoot Overview Source: https://docs.cockroachlabs.com/docs/continuum/tune-and-troubleshoot-overview Performance tuning on Cockroach Continuum Cloud is similar to CockroachDB performance tuning. Statement and index optimization, schema design, and multi-region data placement apply to every cluster. [Cockroach Aegis](/docs/continuum/aegis-overview) supports proactive tuning through recurring check-ins and recommendations, and reactive troubleshooting through alerts and investigations. Use [Ask Aegis](/docs/continuum/aegis-overview#ask-aegis-cluster-aware-qa) in the web UI to explore cluster behavior alongside its analysis, or connect your own agents through [Aegis MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). Use Aegis reports to understand workload changes even when no recommendation is produced. To act on a recommendation, see [Recommendations](/docs/continuum/aegis-overview#recommendations). Pages in this section: * [Performance Best Practices](/docs/stable/performance-best-practices-overview) * [Performance Recipes](/docs/stable/performance-recipes) For worked examples of transaction contention and index recommendations, see [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows). # Build a Go App Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-go # Build a Java App Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-java # Migrate a Sample Database Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-migrate-sample-database > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). In this tutorial, you will migrate a small sample PostgreSQL database to a Cockroach Continuum Cloud cluster with the Migration Assistant, from schema conversion through data verification. Use this tutorial to familiarize yourself with the Migration Assistant's workflow before using it to migrate production data. For detailed information about every stage of the process and the options available during your actual migration, refer to [Use the Migration Assistant](/docs/continuum/migration-assistant-use). The Assistant explains each conversion it makes, and you review and apply every change yourself. The sample database includes a column type, a user-defined function, and a stored procedure. ## Before you begin * This tutorial assumes that you have a Continuum Cloud organization. If you do not yet have one, refer to [Create a Continuum Cloud organization](/docs/continuum/create-a-continuum-organization). * You also need a [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster that meets the [Migration Assistant eligibility requirements](/docs/continuum/migration-assistant-overview#eligibility) as the migration target. The Assistant does not create or configure the target cluster. If you do not yet have a cluster, refer to [Create a Cluster](/docs/continuum/create-a-cluster). * This tutorial requires a PostgreSQL server on version 15 to 18. The server must be reachable from CockroachDB Cloud, and you must have a connection user that can create a database on it. A server bound to `localhost` or reachable only over your VPN does not work. For more information, refer to [Connect your source and target](/docs/continuum/migration-assistant-deploy#connect-your-source-and-target). * To load the sample database, you need access to the `psql` client. * To deploy the Assistant in the Console, your Cockroach Cloud account must have the [Cluster Admin](/docs/cockroachcloud/authorization#cluster-admin) role on the target cluster or the [Organization Admin](/docs/cockroachcloud/authorization#organization-admin) role in the organization. * To deploy the Assistant using the Cloud API, you need an API key for a Cloud API [service account](/docs/cockroachcloud/managing-access) with the Cluster Admin role on the target cluster or the Organization Admin role in the organization. * To reach the Assistant's web interface, your network must be on the target cluster's IP allowlist. ## Step 1. Load the sample database Create the sample database, a miniature vehicle-sharing workload, on your PostgreSQL server. 1. Save the following as `movr_sample.sql`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT NOT NULL, city TEXT NOT NULL ); CREATE TABLE vehicles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), type TEXT NOT NULL, city TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'available' ); CREATE TABLE rides ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), rider_id UUID NOT NULL REFERENCES users (id), vehicle_id UUID NOT NULL REFERENCES vehicles (id), city TEXT NOT NULL, fare MONEY, started_at TIMESTAMPTZ NOT NULL DEFAULT now(), ended_at TIMESTAMPTZ ); CREATE INDEX rides_rider_idx ON rides (rider_id); INSERT INTO users (name, city) VALUES ('Carl Kimball', 'new york'), ('Ollie Gerbich', 'seattle'), ('Havvy Tarbox', 'amsterdam'); INSERT INTO vehicles (type, city) VALUES ('scooter', 'new york'), ('bike', 'seattle'), ('skateboard', 'amsterdam'); INSERT INTO rides (rider_id, vehicle_id, city, fare) SELECT u.id, v.id, u.city, 12.50::money FROM users u JOIN vehicles v ON v.city = u.city; CREATE FUNCTION ride_duration_minutes(started TIMESTAMPTZ, ended TIMESTAMPTZ) RETURNS NUMERIC LANGUAGE SQL AS $$ SELECT EXTRACT(EPOCH FROM (ended - started)) / 60; $$; CREATE PROCEDURE end_ride(ride UUID) LANGUAGE plpgsql AS $$ BEGIN UPDATE rides SET ended_at = now() WHERE id = ride; UPDATE vehicles SET status = 'available' WHERE id = (SELECT vehicle_id FROM rides WHERE id = ride); END; $$; ``` The `fare` column uses the PostgreSQL `MONEY` type, which CockroachDB does not support, so you can see the Assistant work through a conversion decision. 2. Store your PostgreSQL server's connection string in an environment variable. Replace `` with the connection string for your server's default database: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export SOURCE_URL="" ``` 3. Create the database and load the sample: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} psql "$SOURCE_URL" -c 'CREATE DATABASE movr_sample;' psql "$SOURCE_URL/movr_sample" -f movr_sample.sql ``` The second command reports each object as it is created: ``` CREATE TABLE CREATE TABLE CREATE TABLE CREATE INDEX INSERT 0 3 INSERT 0 3 INSERT 0 3 CREATE FUNCTION CREATE PROCEDURE ``` ## Step 2. Deploy the Migration Assistant The Assistant runs as its own instance alongside the target cluster. > [tab] Console > > 1. Log in to the [Cloud Console](https://cockroachlabs.cloud) and select the organization that contains the target cluster. > 2. On the target cluster's **Networking** page, [add your network to the IP allowlist](/docs/cockroachcloud/network-authorization#ip-allowlisting). > 3. In the left navigation, click **Migrations**, then click **New migration**. > 4. Select the **Target cluster**. > 5. Review the **Region**. For a single-region cluster, the region is preselected. For a multi-region cluster, select the region where the Assistant runs. You cannot change the region later without deleting and recreating the instance. > 6. Click **Continue**. The instance appears with status **Deploying**. The page updates automatically; expect provisioning to take 10 to 20 minutes. If the status is **Failed**, the error appears below the status; after addressing its cause, click **Retry deploy**. > 7. When the status is **Ready**, open the target cluster's **Actions** menu and select **Open assistant**. The Assistant opens in a new tab. > 8. Sign in with your Cockroach Cloud account. If the page does not load, confirm that your network is on the cluster's IP allowlist (in the Console, under **Networking**), and allow a few minutes for a new allowlist entry to propagate. > [tab] Cloud API > > Use the following steps to create it by calling the cluster's `migration-assistant` endpoint in the Cloud API. In these steps, replace `{cluster_id}` with the cluster's ID from its overview page in the Console, and `{secret_key}` with your service account's API key. > > 1. Create the instance: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > curl --request POST \ > --url 'https://cockroachlabs.cloud/api/v1/clusters/{cluster_id}/migration-assistant' \ > --header 'Authorization: Bearer {secret_key}' \ > --header 'Content-Type: application/json' \ > --data '{}' > ``` > > The endpoint responds right away, but the instance is not ready yet; the response shows `PENDING`: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "id": "f83ef76b-0e72-4a40-bbcf-a3d6188726f5", > "cluster_id": "c061d097-84b3-4d49-b280-2f579e4a18cb", > "deployed_region": "us-east1", > "status": "PENDING", > "url": "", > "last_error": "", > "created_at": "2026-08-07T17:37:31.235157Z", > "updated_at": "2026-08-07T17:37:31.235157Z", > "username": "", > "password": "", > "bucket_grantee": "", > "health": "NOT_COMPUTED" > } > ``` > > The `id`, `cluster_id`, region, and timestamps shown are specific to your instance. > > 2. Check on provisioning by re-running the following call every 30 to 60 seconds. Expect it to take 10 to 20 minutes. Continue once the status reaches `RUNNING`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > curl --request GET \ > --url 'https://cockroachlabs.cloud/api/v1/clusters/{cluster_id}/migration-assistant' \ > --header 'Authorization: Bearer {secret_key}' > ``` > > Once the instance is ready, the same call returns the address of the Assistant's web interface: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "id": "f83ef76b-0e72-4a40-bbcf-a3d6188726f5", > "cluster_id": "c061d097-84b3-4d49-b280-2f579e4a18cb", > "deployed_region": "us-east1", > "status": "RUNNING", > "url": "https://{assistant_host}", > "last_error": "", > "created_at": "2026-08-07T17:37:31.235157Z", > "updated_at": "2026-08-07T17:40:26.406841Z", > "username": "", > "password": "", > "bucket_grantee": "{bucket_grantee}", > "health": "HEALTHY" > } > ``` > > Record the `url`. The response contains no sign-in credentials, because access to the Assistant uses your CockroachDB Cloud account. > > 3. In a browser, go to the `url` from the previous step and sign in with your Continuum Cloud organization. You must be a member of the organization that owns the target cluster. If the page does not load, confirm that your network is on the cluster's IP allowlist (in the Cloud Console, under **Networking**), and allow a few minutes for a new allowlist entry to propagate. For the full deployment lifecycle, including the status table and troubleshooting, refer to [Deploy the Migration Assistant](/docs/continuum/migration-assistant-deploy). The remaining steps run in the Assistant's web interface: ## Step 3. Connect the source 1. On the **Connect & verify** page, enter the connection string for the `movr_sample` database as the source. 2. The Assistant fills in the target connection for the cluster it is attached to. Confirm that it identifies your cluster. 3. Click **Validate connections**, and fix any reported connectivity or permission problems. 4. Click **Continue**. ## Step 4. Select what to migrate 1. On the **Tables** tab of the **Select objects** page, ensure that `users`, `vehicles`, and `rides` are selected. 2. On the **Routines** tab, ensure that `ride_duration_minutes` and `end_ride` are selected. 3. Click **Save selection**. 4. Click **Continue to Schema conversion**. ## Step 5. Convert the schema 1. The Assistant flags the `rides` table, because CockroachDB does not support the `MONEY` type on the `fare` column. Click **Ask AI to convert these** and wait for the Migration agent to return updated DDL that retypes `fare` as `DECIMAL`, along with an explanation of the change. 2. Click **Apply to Schema** to apply the updated `rides` statement. 3. Click **Continue to Generate plan**. ## Step 6. Generate the plan 1. The Assistant generates your migration plan. For the sample, the plan defers the two foreign keys until after the data load and requires no changes from you. 2. Click **Continue to Pre-migration.** ## Step 7. Prepare the target 1. Under each pre-migration step, click **Execute** to carry out the step. After executing a step, the Assistant automatically expands the next step. 2. Click **Continue to Data load**. ## Step 8. Load the data 1. Click **Execute** on each table batch and wait for `users`, `vehicles`, and `rides` to finish. The sample's nine rows load in moments. Data movement uses the same machinery as [MOLT Fetch](/docs/molt/molt-fetch). 2. Click **Continue to Routine review**. ## Step 9. Create the routines 1. Both of the sample's routines convert cleanly. Click **Create all 2 routines** to create `ride_duration_minutes` and `end_ride` on the target. 2. Click **Run tests to continue** and confirm that both routines pass. 3. Click **Continue to post-migration**. ## Step 10. Finish and verify 1. Click **Execute** under each of the required post-migration steps, which restore the sample's secondary index and deferred foreign keys. 2. Click **Execute** under the optional verification step, which uses the same machinery as [MOLT Verify](/docs/molt/molt-verify). Confirm that all three tables match the source. 3. Click **Continue to results**. ## Step 11. Review the results Confirm that the **Results** page reports every selected object migrated and verified, and that **Objects not migrated** is empty. On a real migration, that list is your remaining work queue, and you would also re-create users, privileges, and any row-level security by hand. For more information, refer to [PostgreSQL compatibility](/docs/continuum/migration-assistant-overview#postgresql-compatibility). ## Step 12. Clean up 1. Save local copies of any converted DDL or generated scripts you still need. The web interface you download them from goes away with the instance. 2. Delete the Assistant instance: > [tab] Console > > In the Console, go to **Migrations**. For the target cluster, open the **Actions** menu and select **Delete migration**. In the confirmation dialog, click **Delete**. The row shows **Deleting** until the instance is removed. > [tab] Cloud API > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > curl --request DELETE \ > --url 'https://cockroachlabs.cloud/api/v1/clusters/{cluster_id}/migration-assistant' \ > --header 'Authorization: Bearer {secret_key}' > ``` 3. Optionally, drop the sample database from your PostgreSQL server: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} psql "$SOURCE_URL" -c 'DROP DATABASE movr_sample;' ``` > [!NOTE] > > The Assistant's scope ends at a converted, loaded, and verified target. It does not run ongoing replication or perform application cutover. For those, refer to [MOLT Replicator](/docs/molt/molt-replicator) and [Migration Best Practices](/docs/molt/migration-strategy). ## What's next * Get more details on each stage of the migration process from [Use the Migration Assistant](/docs/continuum/migration-assistant-use). * [Create Your First Virtual Cluster](/docs/continuum/tutorial-virtual-cluster) # Build a Node.js App Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-nodejs # Build a Python App Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-python # Quickstart with Cockroach Continuum Cloud Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart In this tutorial, you will create your first cluster in a Cockroach Continuum Cloud organization, connect to it, and run your first SQL queries. ## Before you begin You need a Continuum Cloud organization and a running cluster. If you do not have them yet, complete the following steps: 1. [Create a Continuum Cloud organization](/docs/continuum/create-a-continuum-organization). New CockroachDB Cloud organizations use Continuum Cloud by default and receive free trial credits. 2. [Create a cluster](/docs/continuum/create-a-cluster). The Standard edition is recommended for an evaluation cluster. To compare editions, refer to [Editions and Add-Ons](/docs/continuum/editions-and-add-ons). To connect and run queries, you also need one of the following clients: * The CockroachDB CLI (`cockroach`). Continuum Cloud clusters run v26.3 or later. To install the CLI, select your operating system in the **Download the latest CockroachDB Client** section of the Cloud Console's **Connect** dialog, then run the provided command on your command line. * Any PostgreSQL-compatible client, such as `psql`. ## Step 1. Connect to your cluster Connect from your terminal with the CockroachDB CLI, or from your browser with the Cloud Console SQL Shell. The command line is the primary path; the SQL Shell is a browser alternative that needs no local client. > [tab] Command line > > 1. In the Cloud Console, select your cluster, then select **Connect** and copy the general connection string. The connection string embeds credentials, so treat it as a secret and never commit it or paste it into examples. > > 2. In your terminal, store the connection string in an environment variable so it stays out of your shell history. Replace `` in the following command with the value you copied in the previous step: > > ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > export CONTINUUM_CONNECTION_URL="" > ``` > > 3. Open the CockroachDB SQL shell: > > ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > cockroach sql --url "$CONTINUUM_CONNECTION_URL" > ``` > > The terminal displays the SQL shell welcome banner and a prompt that ends with the current database: > > ``` > # > # Welcome to the CockroachDB SQL shell. > # All statements must be terminated by a semicolon. > # To exit, type: \q. > # > # Server version: CockroachDB CCL v26.3.0 > # Cluster ID: > # > # Enter \? for a brief introduction. > # > @:26257/defaultdb> > ``` > > The `Cluster ID`, user, and host shown are specific to your cluster. > > 4. Confirm the connection: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT 1 AS connected; > ``` > > ``` > connected > ------------- > 1 > (1 row) > ``` > [tab] Cloud Console > > > [!NOTE] > > > > The Cloud Console SQL Shell is in preview and requires the Cluster Admin role. It runs statements as the SQL user `root`, and each statement runs in its own transaction, so transaction control statements (`BEGIN`/`COMMIT`), `SET CLUSTER SETTING`, and `CALL` are not supported. The SQL Shell is not available on Mission Critical clusters that have security add-ons configured. > > 1. In the Cloud Console, select your cluster, then open its **SQL Shell** page. You connect in the browser as the SQL user `root`; no connection string or local client is required. > 2. Confirm the connection. Enter the following in the input field, then click **Run**: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT 1 AS connected; > ``` > > The statement status changes to **Succeeds** and the results show a single row with `connected` set to `1`. ## Step 2. Run your first queries Create a small table, write to it, and read it back, using the SQL shell you opened in the previous step. > [tab] Command line > > 1. Create a table: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE roaches (id INT PRIMARY KEY, name STRING); > ``` > > ``` > CREATE TABLE > ``` > > 2. Insert rows: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO roaches (id, name) VALUES (1, 'Roach One'), (2, 'Roach Two'), (3, 'Roach Three'); > ``` > > ``` > INSERT 0 3 > ``` > > 3. Read the rows back: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT id, name FROM roaches ORDER BY id; > ``` > > ``` > id | name > -----+-------------- > 1 | Roach One > 2 | Roach Two > 3 | Roach Three > (3 rows) > ``` > > 4. Remove the table, then exit the shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > DROP TABLE roaches; > ``` > > ``` > DROP TABLE > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q > ``` > [tab] Cloud Console > > In the SQL Shell input field, enter each statement and click **Run** (or press **Enter**). After each statement, the status changes to **Succeeds** or returns an **Error**. You can copy, edit, and re-run any previous statement, and export any results. > > 1. Create a table: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE roaches (id INT PRIMARY KEY, name STRING); > ``` > > The status changes to **Succeeds**. > > 2. Insert rows: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO roaches (id, name) VALUES (1, 'Roach One'), (2, 'Roach Two'), (3, 'Roach Three'); > ``` > > The status changes to **Succeeds**. > > 3. Read the rows back: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT id, name FROM roaches ORDER BY id; > ``` > > The results show three rows: `1, Roach One`; `2, Roach Two`; and `3, Roach Three`. > > 4. Remove the table: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > DROP TABLE roaches; > ``` > > The status changes to **Succeeds**. The SQL Shell stays open in your browser; there is no shell to exit. You now have a working cluster and a verified connection. ## What's next * Work through the [Migrate a Sample Database](/docs/continuum/tutorial-migrate-sample-database) tutorial to migrate an existing database with the [Migration Assistant](/docs/continuum/migration-assistant-overview). * Build an application: refer to [Develop and Connect](/docs/continuum/develop-and-connect-overview). * See where to go at each stage of your Continuum Cloud work in [Get Started with Cockroach Continuum Cloud](/docs/continuum/get-started-with-continuum). # Create Your First Virtual Cluster Source: https://docs.cockroachlabs.com/docs/continuum/tutorial-virtual-cluster > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). Virtual clusters let agents and application developers instantly spin up isolated CockroachDB clusters without requiring newly-provisioned hardware. Virtual clusters are run on top of a host cluster, which serves as the deployed hardware that hosts virtual clusters of varying size and usage. To learn more about virtual clusters, read about [Virtualization in Cockroach Continuum Cloud](/docs/continuum/virtualization-overview). In this tutorial you will create a virtual CockroachDB cluster, connect to it, and interface with a SQL shell. ## Before you begin This tutorial assumes that you have access to a Continuum Cloud organization with a running host cluster. You should have: * A Continuum Cloud organization. Refer to [Create a Continuum Cloud Organization](/docs/continuum/create-a-continuum-organization) to create a new organization if needed, or confirm if your existing CockroachDB deployment is running Continuum Cloud. * A deployed [host cluster](/docs/continuum/workspaces) in the organization. Refer to [Create a Cluster](/docs/continuum/create-a-cluster) if you are creating a host cluster yourself. * Permission to create clusters in the organization. ## Steps In these instructions, you'll use the `ccloud` CLI tool to connect to your organization, create a virtual cluster, and access a SQL shell: 1. Install the [ccloud CLI](/docs/cockroachcloud/ccloud-get-started). To install using Homebrew, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} brew install cockroachdb/tap/ccloud ``` 2. Log in to your Continuum Cloud organization by running the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud auth login ``` Press **Enter** to open a browser window and complete login. To log in on a headless machine, use the `--no-redirect` flag. If you are a member of more than one Cockroach organization, use the `--org` flag to specify the organization label: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud auth login --org {organization-label} ``` 3. Virtual clusters are created inside of a workspace, which sets default configurations for other virtual clusters on that host. Run the following command to list workspaces in the organization: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud workspace list ``` 4. Select a workspace to create your virtual cluster in, then run the following command to create the cluster with a name you specify: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud cluster create --workspace {workspace-name} {cluster-name} ``` ``` ∙∙∙ Creating cluster... Success! Created cluster name: {cluster-name} id: example-67dd-4d25-93b0-91ee7ece778d ``` 5. By default, CockroachDB clusters are locked down to disallow all remote network access. Create an IP allowlist that will allow incoming SQL connections from an IP address or subnet. Run the following command to create an initial entry that allows SQL access for your specific IP address: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud cluster networking allowlist create {cluster-name} {your-ip-address}/32 --sql ``` ``` ∙∙∙ Creating IP allowlist entry... Success! Created IP allowlist entry for network: {your-ip-address}/32 cluster: example-67dd-4d25-93b0-91ee7ece778d ``` Read the [Connect to a Cluster](/docs/cockroachcloud/connect-to-your-cluster) documentation for more information on secure network connectivity options to your virtual cluster. 6. Now, you can connect to your virtual cluster with a SQL shell using the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud cluster sql {cluster-name} ``` This will prompt you to create the first [SQL user](/docs/stable/security-reference/authorization#sql-users) for your cluster. Specify a username and password to create the user, then access the SQL shell: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ∙∙∙ Retrieving cluster info... ∙∙∙ Retrieving SQL user list... No SQL users found. Create one now: y Create a new SQL user: Username: user Password: **************** ∙∙∙ Creating SQL user... Success! Created SQL user name: user cluster: example-67dd-4d25-93b0-91ee7ece778d Starting CockroachDB SQL shell... # # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # # Client version: CockroachDB CCL vXX.2.5 (x86_64-apple-darwin19, built 2022/02/07 21:04:05, go1.16.6) # Server version: CockroachDB CCL vXX.2.4-1-g70835279ac (x86_64-unknown-linux-gnu, built 2022/02/03 22:31:25, go1.16.6) # # Cluster ID: example-67dd-4d25-93b0-91ee7ece778d # # Enter \? for a brief introduction. # ``` Now that you have created a virtual cluster and SQL user, you can establish connections to the cluster with the SQL client or database application of your choice. You can run the following command to get a [PostgreSQL connection URL](/docs/stable/connection-parameters) to your virtual cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud cluster sql --connection-url {cluster-name} ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ∙∙∙ Retrieving cluster info... postgresql://cluster-name-5bct.gcp-us-east4.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fuser%2FLibrary%2FCockroachCloud%2Fcerts%2Fcluster-name-ca.crt ``` ## What's next * [Manage a cluster with the ccloud tool](/docs/cockroachcloud/ccloud-reference). * [Use CockroachDB SQL](/docs/stable/sql-statements). * [Learn more about virtual clusters](/docs/continuum/virtual-clusters). # Tutorials Source: https://docs.cockroachlabs.com/docs/continuum/tutorials-overview This page directs you to step-by-step tutorials for working with CockroachDB on Cockroach Continuum Cloud. The tutorials in this section use standard CockroachDB drivers and tools and work with any Continuum Cloud cluster. ## Get started * Follow [Quickstart with Cockroach Continuum Cloud](/docs/continuum/tutorial-quickstart) to create your first cluster, connect to it, and run your first queries. ## Migrate data * Follow [Migrate a Sample Database](/docs/continuum/tutorial-migrate-sample-database) migrate a sample PostgreSQL database to Continuum Cloud with the Migration Assistant, from schema conversion through data verification. ## Develop and connect * Build an application with a language-specific driver or ORM (Python, Node.js, Go, or Java). Refer to [Develop and Connect](/docs/continuum/develop-and-connect-overview) for language tutorials and connection guidance. ## Manage workloads * Follow [Create Your First Virtual Cluster](/docs/continuum/tutorial-virtual-cluster) after creating a host cluster, to provision your first virtual cluster and connect to it. ## Monitor and optimize * Follow [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows) to run a sample workload against a cluster connected to Cockroach Aegis, understand the transaction contention it reports, and review and apply an index recommendation. # User-Defined Functions Source: https://docs.cockroachlabs.com/docs/continuum/user-defined-functions # Vector Search Source: https://docs.cockroachlabs.com/docs/continuum/vector-search # Virtual Clusters Source: https://docs.cockroachlabs.com/docs/continuum/virtual-clusters > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). A virtual cluster is an isolated cluster created on a host cluster that your organization has already set up. To create a host cluster, refer to [Create a Cluster](/docs/continuum/create-a-cluster). Your organization is billed for the host and [Cluster Virtualization add-on](/docs/continuum/editions-and-add-ons#add-ons); virtual clusters are not billed separately and only share the host's capacity based on usage. An idle virtual cluster consumes no compute. The virtual cluster's data remains on the host cluster and is preserved until the virtual cluster is explicitly deleted. To learn more about virtual cluster concepts, read the [virtualization overview](/docs/continuum/virtualization-overview). ## Create a virtual cluster In order to create a virtual cluster, you must have access to a Cockroach Continuum Cloud organization that has at least one [host cluster and workspace](/docs/continuum/workspaces). A virtual cluster inherits the following configurations from the host and cannot be modified on their own: * **Supported regions**: A virtual cluster can have a custom-set primary region bespoke for that cluster, but a virtual cluster cannot add regions not supported on the host. * **Running CockroachDB version**: The CockroachDB version is inherited from the host; virtual clusters can run one [major version](/docs/releases/index) behind the host cluster. Upgrades to a new version are performed on the host cluster and apply to all virtual clusters on that host. You can create a virtual cluster in the Cloud Console, with the [ccloud CLI](/docs/cockroachcloud/ccloud-get-started), or with the [CockroachDB Cloud API](/docs/cockroachcloud/cloud-api). ### Cloud Console To create a virtual cluster in the Cloud Console, follow these steps: 1. Log in to your Continuum Cloud organization. 2. On the **Clusters** page, click **New cluster** and select a workspace under **Create in workspace**. 3. Review the listed details to confirm the workspace, select regions, and confirm the vCPU burst limit and CockroachDB version inherited from the host cluster. 4. Give your virtual cluster a name, and click **Create cluster**. ### ccloud CLI To create a virtual cluster in the [ccloud CLI](/docs/cockroachcloud/ccloud-get-started), follow these steps: 1. Log into your organization with `ccloud auth`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud auth ``` 2. Run `ccloud workspace list` to list available workspaces: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud workspace list ``` 3. Run `ccloud cluster create --workspace` with the workspace name and a cluster name to create a virtual cluster in that workspace: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud cluster create --workspace {workspace-name} {cluster-name} ``` See the [Create a Virtual Cluster tutorial](/docs/continuum/tutorial-virtual-cluster) for more detailed instructions using the `ccloud` CLI. ### Cloud API To create a virtual cluster, send a `POST` request to the `/v1/virtual-cluster-workspaces/{workspace_id}/clusters` endpoint, specifying the cluster name. The service account associated with the secret key must have the Cluster Admin or Cluster Creator [role](/docs/cockroachcloud/authorization#organization-user-roles). ```shell curl theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request POST \ --url https://cockroachlabs.cloud/api/v1/virtual-cluster-workspaces/{workspace_id}/clusters \ --header "Authorization: Bearer {secret_key}" \ --json '{"name":"{cluster_name}"}' ``` ```json Expanded JSON (Virtual cluster creation format) theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "name": "{cluster_name}" } ``` To list the workspaces available in an organization, send a `GET` request to the `/v1/virtual-cluster-workspaces` endpoint: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request GET \ --url https://cockroachlabs.cloud/api/v1/virtual-cluster-workspaces \ --header "Authorization: Bearer {secret_key}" ``` ## Connect to a virtual cluster Each virtual cluster on a host has its own network security configuration, PostgreSQL connection string, and its own SQL users. Refer to the [Connect to a Cluster](/docs/cockroachcloud/connect-to-your-cluster) documentation for more information on network connectivity and security. An application connecting to a virtual cluster cannot see or reach the host or any other virtual cluster in the workspace; no network configuration is necessary to ensure this level of isolation. ### PostgreSQL connection string To generate the connection string for a virtual cluster, you can either navigate to the cluster in the Cloud Console and click the **Connect** button, or use the [ccloud CLI](/docs/cockroachcloud/ccloud-reference#get-connection-information-for-a-cluster). On the first connection to a newly created cluster, you will be prompted to first create a SQL user. Learn more about SQL users in the [authorization documentation](/docs/stable/security-reference/authorization#sql-users). ### Model Context Protocol (MCP) You can connect to a virtual cluster with the [CockroachDB MCP server](/docs/stable/cockroachdb-mcp-server). In the Cloud console, open the virtual cluster and click **Connect -> Model Context Protocol (MCP)** for specific instructions to set up different MCP clients to connect to the cluster. ## Scaling behavior You do not size a virtual cluster. Virtual clusters scale with their workload, up to the maximum compute measured as a vCPU "burst limit". The default burst limit is set by the cluster's workspace at creation time of the virtual cluster. You can directly modify the burst limit of an individual virtual cluster, but this operation requires that you have the necessary permissions to modify the host cluster configuration as well. An idle virtual cluster scales to zero and holds no compute. Its data remains durable on the host. ## Deletion Delete a virtual cluster to remove it from the host cluster. Deletion has a 4-hour grace period: SQL connections are rejected immediately, but data is preserved and the deletion can be canceled. After the grace period the virtual cluster is removed, and its backups are retained for the shorter of the backup retention period or 30 days. ## Backup and restore Backups are stored per virtual cluster. Each virtual cluster can have its own backup destination, and restores target one virtual cluster without affecting the host's other virtual clusters. ## Monitor a virtual cluster The Cloud Console shows per-virtual-cluster metrics: CPU, queries per second, storage, and connections. Continuum Cloud administrators can monitor individual virtual clusters as needed, but best practice is to monitor at the [host cluster and workspace](/docs/continuum/workspaces) level with observability tooling for ease of management. Metrics can be [exported to Prometheus or Datadog](/docs/cockroachcloud/export-metrics). ## Feature availability on virtual clusters Virtual clusters inherit the host's license entitlements, but not every cluster feature applies to a virtual cluster. | Feature | On a virtual cluster | | - | - | | [Backups with revision history and PITR](/docs/stable/take-backups-with-revision-history-and-restore-from-a-point-in-time) | ✓ | | Scheduled backups and restore | ✓ | | [Encrypted backups](/docs/stable/take-and-restore-encrypted-backups) | ✓ | | [Row-level security](/docs/stable/row-level-security) | ✓ | | [Column-level encryption](/docs/stable/column-level-encryption) | ✓ | | [Changefeeds (CDC)](/docs/stable/change-data-capture-overview) | ✓ (requires the host cluster to have the [Data Sync](/docs/continuum/editions-and-add-ons#add-ons) add-on) | | Ingress private link | ✓ | | [Online restore](/docs/stable/restore) | ✗ (only on the [Mission Critical](/docs/continuum/editions-and-add-ons#editions) host itself) | | [CMEK](/docs/cockroachcloud/cmek) | ✗ (applies at the host cluster level and covers the host's virtual clusters through the host's key) | | [Physical cluster replication](/docs/stable/physical-cluster-replication-overview) | ✗ | | [Egress private link](/docs/cockroachcloud/egress-private-endpoints) | ✗ | | [Egress perimeter control](/docs/cockroachcloud/egress-perimeter-controls) | ✗ | ## Known limitations * A virtual cluster runs only within its host's regional footprint. * Virtual clusters support up to approximately 10,000 schema objects per cluster. * The CockroachDB version is inherited from the host and cannot be set per virtual cluster. * Moving a virtual cluster to another host requires backup and restore with downtime. * There is no separate RBAC model for virtual clusters. Existing cluster roles and permissions apply. # Virtualization Architecture Source: https://docs.cockroachlabs.com/docs/continuum/virtualization-architecture > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). This page describes how Cockroach Continuum Cloud virtualization works: how virtual clusters share a host cluster's hardware while keeping data, schema, and workloads isolated, and where the platform enforces the policies attached to a [workspace](/docs/continuum/workspaces). ## Overview A [host cluster](/docs/continuum/workspaces) is a CockroachDB cluster whose nodes provide storage and compute for many tenants. Each [virtual cluster](/docs/continuum/virtual-clusters) is a tenant: it has its own portion of the keyspace, its own catalog and users, and its own SQL runtime, while sharing the host's replicated storage layer. The Continuum control plane creates virtual clusters on hosts, routes each connection to the target virtual cluster, and applies the workspace's policies when a virtual cluster is created or changed. ## Host clusters A host is a [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster with virtualization enabled at creation. A host cluster's capacity is accounted in vCPUs. The platform tracks total capacity against the capacity reserved by its virtual clusters. Host clusters have a minimum size of 3 nodes and 4 vCPUs per node, run on AWS or GCP, and are limited to 3 per organization. ## Virtual cluster internals Each virtual cluster's data lives in its own keyspace prefix on the host, so one virtual cluster cannot name, read, or write another's tables. Schema metadata, users, and privileges are per virtual cluster. SQL execution for a virtual cluster runs in its own processes, which start on demand and stop when the virtual cluster is idle. Connection routing inspects the connection and delivers it to the target virtual cluster's SQL layer. A virtual cluster supports on the order of 10,000 schema objects. This limit is per virtual cluster, not shared across the host. ## Resource management and admission control Virtual clusters draw compute from the host on demand. [Admission control](/docs/stable/admission-control) meters CPU time per virtual cluster, so a high-traffic virtual cluster cannot starve its neighbors. Each virtual cluster has a default compute ceiling set by its workspace. The sum of all ceilings across virtual clusters can exceed the host's total capacity. This is by design; a ceiling is not a reservation, and no resources are pre-allocated. Virtual clusters only consume what they actively use. > [!NOTE] > > Admission control bounds how much a virtual cluster can consume. It does not reserve a minimum for it. ## Data placement, backups, and replication A virtual cluster's data is replicated by the host like any other data on the host, and inherits the host's regional footprint. Backups are taken per virtual cluster, each to its own destination. Restores are scoped to a single virtual cluster without affecting its neighbors. Moving a virtual cluster to a different host is a backup and restore operation and involves downtime. No online migration tooling is available. ## Observability boundaries Application teams see metrics for their own virtual cluster: CPU, queries per second, storage, and connections. Platform teams additionally see the host-level view. Customer access to the host's system tenant is read-only. Metrics can be [exported to Prometheus or Datadog](/docs/cockroachcloud/export-metrics). ## Known limitations * 3 host clusters per organization. * Hosts run on AWS and GCP only. * Virtualization is chosen at host creation. An existing cluster cannot be converted into a host. * On the order of 10,000 schema objects per virtual cluster. * No per-virtual-cluster minimum-CPU guarantees. * Moving a virtual cluster between hosts requires backup and restore with downtime. # Virtualization Overview Source: https://docs.cockroachlabs.com/docs/continuum/virtualization-overview > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). Unlike a traditional database deployment, where every application that needs an isolated database requires a standalone infrastructure deployment with its own provisioning, billing, and operation, use virtual clusters with the [Cluster Virtualization Add-on](/docs/continuum/editions-and-add-ons#add-ons) in CockroachDB to quickly deploy multiple isolated databases on shared infrastructure. Create a *host cluster* in a CockroachDB organization, and you can create *virtual clusters* on the host cluster's capacity. Each virtual cluster has its own connection string, users, schemas, and backups, is isolated from its neighbors on the same host cluster, and is governed by configurable policies. Creation of a virtual cluster does not require you to provision new infrastructure, enabling rapid deployment of isolated databases with the [benefits of CockroachDB](/docs/stable/why-cockroachdb). ## Use cases Virtual clusters are ideal for organizations that need many isolated databases without the cost and complexity of a provisioned cluster per workload. With a dedicated host cluster created and provisioned with redundant architecture and maximum capacity, any number of virtual clusters can be created that share the total capacity of the host. This architecture supports rapid deployment of secure, isolated, resilient databases with no administrative overhead, maximizing the resource utilization of the provisioned host cluster. Some example use cases served well by this architecture include: * Engineers and/or agents needing to deploy database instances for business application development with resiliency. * Organizations that want to run multiple isolated databases of varying sizes and workloads without provisioning new infrastructure for each. * Administrators of an existing CockroachDB deployment wanting to support application development at agentic speeds without the overhead of provisioning physical cluster and observability infrastructure. > [!CAUTION] > > Virtual clusters are not recommended for tier 0 applications and workloads such as payments, authorizations, and order processing. Consider a dedicated [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster for these workloads. ## Key concepts * A *host cluster* is a [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster created with the **Cluster Virtualization** add-on. This option is only available when you [create the cluster](/docs/continuum/create-a-cluster); an existing cluster cannot be converted to a host cluster. The host cluster provides the hardware that virtual clusters share. A host cluster behaves like any other CockroachDB cluster with its own nodes and the Mission Critical feature set. * A *virtual cluster* is an isolated cluster created on a host. Virtual clusters are CockroachDB clusters, with their own connection strings, users, and schemas. A virtual cluster's usage consumes the host's capacity and is not billed separately. * A *workspace* groups virtual clusters on a host cluster and defines default configurations for the virtual clusters created within, such as setting the default max compute. Developers select a workspace when creating a virtual cluster. To deploy a host cluster and prepare a workspace, read [Host Clusters and Workspaces](/docs/continuum/workspaces). To deploy and use a virtual cluster, read [Virtual Clusters](/docs/continuum/virtual-clusters) or follow the [Create Your First Virtual Cluster tutorial](/docs/continuum/tutorial-virtual-cluster). ## Workload isolation Each virtual cluster is isolated from other virtual clusters on the same host. Its data, SQL runtime, users, and schemas are its own, and connections route only to it, so an application connected to one virtual cluster cannot see or access another's data. Data is isolated at the database layer, through enforcement at the SQL and admission-control layers. Virtual clusters on the same host share only the underlying physical storage infrastructure. ## CPU management CPU is managed automatically. CockroachDB tracks CPU usage per virtual cluster and throttles any that exceeds its isolated share, which is the same approach used by CockroachDB to manage [multi-tenant CockroachDB Cloud deployments](/docs/cockroachcloud/security-overview). CPU management on host clusters works at two layers, the SQL layer and KV layer: * **SQL layer**: Every virtual cluster has a default "burst limit", which is the maximum CPU that it can consume at any point. A virtual cluster cannot exceed this limit regardless of how much capacity is available on the host. * **KV layer**: When multiple virtual clusters are active simultaneously, CockroachDB distributes CPU fairly among them. No single virtual cluster is allowed to monopolize the host cluster's resources at the expense of others. ## Roles and responsibilities The host and virtual cluster architecture is designed for two roles: * A platform team that owns the shared host infrastructure. They create and manage host clusters, define workspaces, and set the policies that control what application teams do. The platform team has visibility across all hosts and virtual clusters. * Application teams and/or agents that create, manage, and use virtual clusters within the workspaces the platform team has configured for them. Their visibility is limited to their own virtual clusters; they cannot see or access other teams' data or virtual clusters. These capabilities are controlled through CockroachDB's privilege system. A user can perform actions associated with the platform or application team based on the privileges granted to their role. For details on roles and privileges in CockroachDB, see the [authorization in CockroachDB](/docs/stable/security-reference/authorization) and [CockroachDB Cloud access management](/docs/cockroachcloud/authorization) documentation. ## See also * [Virtualization Architecture](/docs/continuum/virtualization-architecture) * [Virtual Clusters](/docs/continuum/virtual-clusters) * [Workspaces and Host Clusters](/docs/continuum/workspaces) * [Editions and Add-Ons](/docs/continuum/editions-and-add-ons) # Workspaces and Host Clusters Source: https://docs.cockroachlabs.com/docs/continuum/workspaces > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). This page describes how to create workspaces and host clusters, and how they act as containers of virtual clusters. ## Key concepts A workspace groups [virtual clusters](/docs/continuum/virtual-clusters) on a host cluster and defines default configurations for the virtual clusters created within, such as setting the default max compute. Developers select a workspace when creating a virtual cluster. A host cluster is a [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster created with the Cluster Virtualization add-on, which enables virtualization. Virtualization can only be enabled on cluster creation; an existing cluster cannot be converted into a host. In every other respect a host behaves like a Mission Critical cluster, and you scale and operate it like any dedicated cluster hardware. You pay for the host and the [Cluster Virtualization add-on](/docs/continuum/editions-and-add-ons#add-ons). The virtual clusters on it carry no separate charge. Each host cluster has one workspace, created with the host, with permissive default policies. ## Capacity planning and utilization Host clusters have a minimum size of 3 nodes with 4 vCPUs each. You may want to increase capacity and node count based on the anticipated growth of virtual cluster count and usage within your organization, but because virtual clusters themselves scale automatically and have a controlled vCPU burst limit, you can provision a smaller configuration and use observability tools on the host to determine if growth is necessary. > [!CAUTION] > > Virtual clusters are not recommended for tier 0 applications and workloads such as payments, authorizations, and order processing. Consider a dedicated [Mission Critical](/docs/continuum/editions-and-add-ons#editions) cluster for these workloads. Cockroach Continuum Cloud tracks the host's total capacity against the capacity reserved by its virtual clusters, which shows the headroom remaining before you create more virtual clusters or scale the host. ## Host configuration inheritance When a virtual cluster is created, it inherits some configuration details from the host cluster that can not be configured on the virtual cluster itself. Note the following before creating a host cluster: * **Supported regions**: A virtual cluster can have a custom-set primary region bespoke for that cluster, but a virtual cluster cannot add regions not supported on the host. * **Running CockroachDB version**: The CockroachDB version is inherited from the host. Upgrades to a new version are performed on the host cluster and apply to all virtual clusters on that host. These host configuration inheritance restrictions are different from workspaces, which assign a default configuration to clusters created within but can also be adjusted on a per-cluster basis. ### Workspace policies Workspaces can be configured to enforce the maximum compute per virtual cluster. Each virtual cluster created in a workspace is assigned a default compute ceiling of 50% of the host cluster's total capacity. Ceilings are defaults, not reservations, and the sum of ceilings can exceed the host's capacity. A workspace's policies are enforced when a virtual cluster is created in the workspace. ## Create a host cluster and workspace You can create a host cluster in the Cloud Console, with the [ccloud CLI](/docs/cockroachcloud/ccloud-get-started), or with the [CockroachDB Cloud API](/docs/cockroachcloud/cloud-api). ### Cloud Console To create a host cluster in the Cloud Console, follow these steps: 1. Log in to your Continuum Cloud organization. 2. On the **Clusters** page, click **New cluster -> Create cluster**. 3. Select the **Mission Critical** edition. 4. Enable the **Dedicated host** toggle. 5. Configure your host cluster as desired, considering how you want to [provision the host capacity](#capacity-planning-and-utilization) and [configuration inheritance](#host-configuration-inheritance). 6. Click **Create cluster**. After cluster creation is started, you will be prompted to name the workspace on this host cluster. This workspace name is how users creating a virtual cluster will select a host, not the host name itself, so best practice is to give this workspace a descriptive name such as a team or project. By default the vCPU burst limit is set to 1/2 of the total provisioned vCPU on the host cluster. This value can be modified for a workspace using the `ccloud` CLI or the Cloud API. ### ccloud CLI To create a host cluster using the [ccloud CLI](/docs/cockroachcloud/ccloud-get-started), follow these steps: 1. Log into your organization with `ccloud auth`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud auth ``` 2. Run `ccloud cluster create mission-critical` with the `--dedicated-host` flag to create a host cluster, and the desired values for the cluster configuration with consideration for how you want to [provision the host capacity](#capacity-planning-and-utilization) and [configuration inheritance](#host-configuration-inheritance): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud cluster create mission-critical {cluster-name} us-east-1:3 --cloud AWS --vcpus 4 --storage-gib 110 --dedicated-host ``` 3. When a host cluster is created, a default workspace is created that inherits the host cluster's name and sets the default vCPU burst limit to 1/2 of the total provisioned vCPU on the host cluster. To modify the workspace name and configuration: 1. List workspaces in the organization to get the of the newly-created workspace: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud workspace list ``` 2. Update the name and configuration as desired. This workspace name is how users creating a virtual cluster will select a host, not the host name itself, so best practice is to give this workspace a descriptive name such as a team or project: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ccloud workspace update {workspace-id} --name {new-workspace-name} --default-virtual-cpu-burst-limit {new-burst-limit} ``` You can omit `--name` or `--default-virtual-cpu-burst-limit` to leave their value as-is. Note that modifying the workspace configuration only updates the default configuration applied to newly-created virtual clusters in the workspace, not any virtual clusters that are already deployed. ### Cloud API To create a host cluster with the [Cloud API](/docs/cockroachcloud/cloud-api), send a `POST` request to the `/v1/clusters` endpoint. The service account associated with the secret key must have the Cluster Admin or Cluster Creator [role](/docs/cockroachcloud/authorization#organization-user-roles). ```shell curl theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request POST \ --url https://cockroachlabs.cloud/api/v1/clusters \ --header "Authorization: Bearer {secret_key}" \ --json '{"name":"{cluster_name}","provider":"{cloud_provider}","edition":"MISSION_CRITICAL","spec":{"host":{"region_nodes":{"{region_name}":3},"hardware":{"machine_spec":{"num_virtual_cpus":{num_vcpus}}},"cockroach_version":"{version}"}}}' ``` ```json Expanded JSON (Host cluster creation format) theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "name":"{cluster_name}", "provider":"{cloud_provider}", "edition":"MISSION_CRITICAL", "spec":{ "host":{ "region_nodes":{ "{region_name}":3 }, "hardware":{ "machine_spec":{ "num_virtual_cpus":{num_vcpus} } },"cockroach_version":"{version}" } } } ``` Set the parameter fields as desired for your configuration, with consideration for how you want to [provision the host capacity](#capacity-planning-and-utilization) and [configuration inheritance](#host-configuration-inheritance): * `{cluster_name}` is the name of the cluster. The name must be 6-20 characters in length and can include numbers, lowercase letters, and dashes (but no leading or trailing dashes). * `{cloud_provider}` is the name of the cloud provider on which you want your cluster to run: AWS or GCP. * `edition` is set to MISSION_CRITICAL for a host cluster. * `{region_name}` is the name of a CockroachDB Cloud region. Region names are set by the cloud provider. For example, `us-east-1` is an AWS region. Available regions vary based on the cloud provider. * `region_nodes` specifies the number of nodes in each region. The minimum is 3 nodes per region for a Mission Critical/host cluster. * `{num_vcpus}` is the number of virtual CPUs per node in the cluster. This value determines the machine type that is provisioned. Host clusters require a minimum of 4 vCPUs. * `{version}` is the CockroachDB version for the cluster. When a host cluster is created, a default workspace is created that inherits the host cluster's name and sets the default vCPU burst limit to 1/2 of the total provisioned vCPU on the host cluster. To modify the workspace name and configuration, first send a `GET` request to the `/v1/virtual-cluster-workspaces` endpoint to get the `{workspace-id}` of the newly-created workspace ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request GET \ --url https://cockroachlabs.cloud/api/v1/virtual-cluster-workspaces \ --header "Authorization: Bearer {secret_key}" ``` Send a `PATCH` request to the `/v1/virtual-cluster-workspaces/{workspace-id}` endpoint to modify the name and configuration of the workspace as desired. This workspace name is how users creating a virtual cluster will select a host, not the host name itself, so best practice is to give this workspace a descriptive name such as a team or project: ```shell curl theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --request PATCH \ --url https://cockroachlabs.cloud/api/v1/virtual-cluster-workspaces/{workspace-id} \ --header "Authorization: Bearer {secret_key}" \ --json '{"name":"{new_workspace_name}","default_virtual_cpu_burst_limit":"{value}"}' ``` ```json Expanded JSON (Workspace configuration creation format) theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "name":"{new-workspace-name}", "default_virtual_cpu_burst_limit":"{value}" } ``` You can omit any of the workspace parameters to leave the value as-is. Note that modifying the workspace configuration only updates the default configuration applied to newly-created virtual clusters in the workspace, not any virtual clusters that are already deployed. ## Access control Host clusters use Cockroach Cloud [cluster roles and permissions](/docs/cockroachcloud/authorization), there are no bespoke access controls for cluster virtualization. ## Lifecycle and limits * An organization can have up to 3 host clusters. * Hosts run on AWS and GCP only. * A host cluster cannot be deleted while virtual clusters exist on it. * Virtualization cannot be added to or removed from an existing cluster. * A host cluster can only support one workspace. # Build a C# App with CockroachDB and the .NET Npgsql Driver Source: https://docs.cockroachlabs.com/docs/stable/build-a-csharp-app-with-cockroachdb This tutorial shows you how build a simple C# application with CockroachDB and the .NET Npgsql driver. ## Start CockroachDB Choose whether to run a temporary local cluster or a free CockroachDB cluster on CockroachDB Basic. The instructions below will adjust accordingly. > [tab] Use CockroachDB Basic > > ### Create a free cluster > > > [!NOTE] > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > 1. If you haven't already, sign up for a CockroachDB Cloud account. > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > 3. On the **Clusters** page, click **Create cluster**. > 4. On the **Select a plan** page, select **Basic**. > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > 7. Click **Next: Capacity**. > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > 9. On the **Finalize** page, click **Create cluster**. > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > ### Set up your cluster connection > > The **Connection info** dialog shows information about how to connect to your cluster. > > 1. Click the **Choose your OS** dropdown, and select the operating system of your local machine. > > 2. Click the **Connection string** tab in the **Connection info** dialog. > > 3. Open a new terminal on your local machine, and run the command provided in step **1** to download the CA certificate. This certificate is required by some clients connecting to CockroachDB Cloud. > > 4. Copy the connection string provided in step **2** to a secure location. > > > [!NOTE] > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/v26.4/install-cockroachdb-mac). > > 2. Run the [`cockroach demo`](/docs/v26.4/cockroach-demo) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach demo \ > --no-example-database > ``` > > This starts a temporary, in-memory cluster and opens an interactive SQL shell to the cluster. Any changes to the database will not persist after the cluster is stopped. > > > [!NOTE] > > > > If `cockroach demo` fails due to SSL authentication, make sure you have cleared any previously downloaded CA certificates from the directory `~/.postgresql`. > > 1. Take note of the `(sql)` connection string in the SQL shell welcome text: > > ``` > # Connection parameters: > # (webui) http://127.0.0.1:8080/demologin?password=demo76950&username=demo > # (sql) postgres://demo:demo76950@127.0.0.1:26257?sslmode=require > # (sql/unix) postgres://demo:demo76950@?host=%2Fvar%2Ffolders%2Fc8%2Fb_q93vjj0ybfz0fz0z8vy9zc0000gp%2FT%2Fdemo070856957&port=26257 > ``` ## Create a .NET project In your terminal, run the following commands: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} dotnet new console -o cockroachdb-test-app ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cd cockroachdb-test-app ``` The `dotnet` command creates a new app of type `console`. The `-o` parameter creates a directory named `cockroachdb-test-app` where your app will be stored and populates it with the required files. The `cd cockroachdb-test-app` command puts you into the newly created app directory. ## Install the Npgsql driver Install the latest version of the [Npgsql driver](https://www.nuget.org/packages/Npgsql/) into the .NET project using the built-in nuget package manager: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} dotnet add package Npgsql ``` ## Create a database > [tab] Use CockroachDB Basic > > 1. If you haven't already, [download the CockroachDB binary](/docs/v26.4/install-cockroachdb-mac). > > 2. Start the [built-in SQL shell](/docs/v26.4/cockroach-sql) using the connection string you got from the CockroachDB Cloud Console: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql \ > --url=' ``` > > 3. In the SQL shell, create the `bank` database that your application will use: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > 4. Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > [tab] Use a Local Cluster > > 1. In the SQL shell, create the `bank` database that your application will use: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > 2. Create a SQL user for your app: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER WITH PASSWORD ; > ``` > > Take note of the username and password. You will use it in your application code later. > > 3. Give the user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO ; > ``` ## Set the connection string > [tab] macOS / Linux > > Set a `DATABASE_URL` environment variable to your connection string. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > export DATABASE_URL="{connection string}" > ``` > [tab] Windows > > Set a `DATABASE_URL` environment variable to your connection string. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $env:DATABASE_URL = "{connection string}" > ``` ## Run the C# code Now that you have set up your project and created a database, in this section you will: * [Create a table and insert some rows](#basic-example) * [Execute a batch of statements as a transaction](#transaction-example-with-retry-logic) ### Basic example #### Get the code Replace the contents of the `Program.cs` file that was automatically generated in your `cockroachdb-test-app` directory with the code below: ```c# theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} using System; using System.Data; using System.Net.Security; using Npgsql; namespace Cockroach { class MainClass { static void Main(string[] args) { var connStringBuilder = new NpgsqlConnectionStringBuilder(); connStringBuilder.SslMode = SslMode.VerifyFull; string? databaseUrlEnv = Environment.GetEnvironmentVariable("DATABASE_URL"); if (databaseUrlEnv == null) { connStringBuilder.Host = "localhost"; connStringBuilder.Port = 26257; connStringBuilder.Username = "{username}"; connStringBuilder.Password = "{password}"; } else { Uri databaseUrl = new Uri(databaseUrlEnv); connStringBuilder.Host = databaseUrl.Host; connStringBuilder.Port = databaseUrl.Port; var items = databaseUrl.UserInfo.Split(new[] { ':' }); if (items.Length > 0) connStringBuilder.Username = items[0]; if (items.Length > 1) connStringBuilder.Password = items[1]; } connStringBuilder.Database = "bank"; Simple(connStringBuilder.ConnectionString); } static void Simple(string connString) { using (var conn = new NpgsqlConnection(connString)) { conn.Open(); // Create the "accounts" table. using (var cmd = new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn)) { cmd.ExecuteNonQuery(); } // Insert two rows into the "accounts" table. using (var cmd = new NpgsqlCommand()) { cmd.Connection = conn; cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)"; cmd.Parameters.AddWithValue("id1", 1); cmd.Parameters.AddWithValue("val1", 1000); cmd.Parameters.AddWithValue("id2", 2); cmd.Parameters.AddWithValue("val2", 250); cmd.ExecuteNonQuery(); } // Print out the balances. System.Console.WriteLine("Initial balances:"); using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) using (var reader = cmd.ExecuteReader()) while (reader.Read()) Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); } } } } ``` #### Run the basic example Compile and run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} dotnet run ``` The output should be: ``` Initial balances: account 1: 1000 account 2: 250 ``` ### Transaction example (with retry logic) #### Modify the code Open `cockroachdb-test-app/Program.cs` again and replace the contents with the code shown below. > [tab] Use a Local Cluster > > ```c# theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > using System; > using System.Data; > using System.Net.Security; > using Npgsql; > > namespace Cockroach > { > class TransactionsClass > { > static void Main(string[] args) > { > var connStringBuilder = new NpgsqlConnectionStringBuilder(); > connStringBuilder.SslMode = SslMode.VerifyFull; > // use the DATABASE_URL environment variable if it is set > string? databaseUrlEnv = Environment.GetEnvironmentVariable("DATABASE_URL"); > if (databaseUrlEnv == null) { > connStringBuilder.Host = "localhost"; > connStringBuilder.Port = 26257; > connStringBuilder.Username = "{username}"; > connStringBuilder.Password = "{password}"; > } else { > Uri databaseUrl = new Uri(databaseUrlEnv); > connStringBuilder.Host = databaseUrl.Host; > connStringBuilder.Port = databaseUrl.Port; > var items = databaseUrl.UserInfo.Split(new[] { ':' }); > if (items.Length > 0) connStringBuilder.Username = items[0]; > if (items.Length > 1) connStringBuilder.Password = items[1]; > } > connStringBuilder.Database = "bank"; > TxnSample(connStringBuilder.ConnectionString); > } > > static void TransferFunds(NpgsqlConnection conn, NpgsqlTransaction tran, int from, int to, int amount) > { > int balance = 0; > using (var cmd = new NpgsqlCommand(String.Format("SELECT balance FROM accounts WHERE id = {0}", from), conn, tran)) > using (var reader = cmd.ExecuteReader()) > { > if (reader.Read()) > { > balance = reader.GetInt32(0); > } > else > { > throw new DataException(String.Format("Account id={0} not found", from)); > } > } > if (balance < amount) > { > throw new DataException(String.Format("Insufficient balance in account id={0}", from)); > } > using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance - {0} where id = {1}", amount, from), conn, tran)) > { > cmd.ExecuteNonQuery(); > } > using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance + {0} where id = {1}", amount, to), conn, tran)) > { > cmd.ExecuteNonQuery(); > } > } > > static void TxnSample(string connString) > { > using (var conn = new NpgsqlConnection(connString)) > { > conn.Open(); > > // Create the "accounts" table. > new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery(); > > // Insert two rows into the "accounts" table. > using (var cmd = new NpgsqlCommand()) > { > cmd.Connection = conn; > cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)"; > cmd.Parameters.AddWithValue("id1", 1); > cmd.Parameters.AddWithValue("val1", 1000); > cmd.Parameters.AddWithValue("id2", 2); > cmd.Parameters.AddWithValue("val2", 250); > cmd.ExecuteNonQuery(); > } > > // Print out the balances. > System.Console.WriteLine("Initial balances:"); > using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) > using (var reader = cmd.ExecuteReader()) > while (reader.Read()) > Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); > > try > { > using (var tran = conn.BeginTransaction()) > { > tran.Save("cockroach_restart"); > while (true) > { > try > { > TransferFunds(conn, tran, 1, 2, 100); > tran.Commit(); > break; > } > catch (NpgsqlException e) > { > // Check if the error code indicates a SERIALIZATION_FAILURE. > if (e.ErrorCode == 40001) > { > // Signal the database that we will attempt a retry. > tran.Rollback("cockroach_restart"); > } > else > { > throw; > } > } > } > } > } > catch (DataException e) > { > Console.WriteLine(e.Message); > } > > // Now printout the results. > Console.WriteLine("Final balances:"); > using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) > using (var reader = cmd.ExecuteReader()) > while (reader.Read()) > Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); > } > } > } > } > ``` > [tab] Use CockroachDB Basic > > ```c# theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > using System; > using System.Data; > using System.Net.Security; > using Npgsql; > > namespace Cockroach > { > class MainClass > { > static void Main(string[] args) > { > var connStringBuilder = new NpgsqlConnectionStringBuilder(); > connStringBuilder.SslMode = SslMode.VerifyFull; > connStringBuilder.Host = "{host-name}"; > connStringBuilder.Port = 26257; > connStringBuilder.Username = "{username}"; > connStringBuilder.Password = "{password}"; > connStringBuilder.Database = "bank"; > TxnSample(connStringBuilder.ConnectionString); > } > > static void TransferFunds(NpgsqlConnection conn, NpgsqlTransaction tran, int from, int to, int amount) > { > int balance = 0; > using (var cmd = new NpgsqlCommand(String.Format("SELECT balance FROM accounts WHERE id = {0}", from), conn, tran)) > using (var reader = cmd.ExecuteReader()) > { > if (reader.Read()) > { > balance = reader.GetInt32(0); > } > else > { > throw new DataException(String.Format("Account id={0} not found", from)); > } > } > if (balance < amount) > { > throw new DataException(String.Format("Insufficient balance in account id={0}", from)); > } > using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance - {0} where id = {1}", amount, from), conn, tran)) > { > cmd.ExecuteNonQuery(); > } > using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance + {0} where id = {1}", amount, to), conn, tran)) > { > cmd.ExecuteNonQuery(); > } > } > > static void TxnSample(string connString) > { > using (var conn = new NpgsqlConnection(connString)) > { > conn.Open(); > > // Create the "accounts" table. > new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery(); > > // Insert two rows into the "accounts" table. > using (var cmd = new NpgsqlCommand()) > { > cmd.Connection = conn; > cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)"; > cmd.Parameters.AddWithValue("id1", 1); > cmd.Parameters.AddWithValue("val1", 1000); > cmd.Parameters.AddWithValue("id2", 2); > cmd.Parameters.AddWithValue("val2", 250); > cmd.ExecuteNonQuery(); > } > > // Print out the balances. > System.Console.WriteLine("Initial balances:"); > using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) > using (var reader = cmd.ExecuteReader()) > while (reader.Read()) > Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); > > try > { > using (var tran = conn.BeginTransaction()) > { > tran.Save("cockroach_restart"); > while (true) > { > try > { > TransferFunds(conn, tran, 1, 2, 100); > tran.Commit(); > break; > } > catch (NpgsqlException e) > { > // Check if the error code indicates a SERIALIZATION_FAILURE. > if (e.ErrorCode == 40001) > { > // Signal the database that we will attempt a retry. > tran.Rollback("cockroach_restart"); > } > else > { > throw; > } > } > } > } > } > catch (DataException e) > { > Console.WriteLine(e.Message); > } > > // Now printout the results. > Console.WriteLine("Final balances:"); > using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) > using (var reader = cmd.ExecuteReader()) > while (reader.Read()) > Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); > } > } > } > } > ``` ```c# theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} using System; using System.Data; using System.Net.Security; using Npgsql; namespace Cockroach { class MainClass { static void Main(string[] args) { var connStringBuilder = new NpgsqlConnectionStringBuilder(); connStringBuilder.Host = "{host-name}"; connStringBuilder.Port = 26257; connStringBuilder.SslMode = SslMode.VerifyFull; connStringBuilder.Username = "{username}"; connStringBuilder.Password = "{password}"; connStringBuilder.Database = "bank"; TxnSample(connStringBuilder.ConnectionString); } static void TransferFunds(NpgsqlConnection conn, NpgsqlTransaction tran, int from, int to, int amount) { int balance = 0; using (var cmd = new NpgsqlCommand(String.Format("SELECT balance FROM accounts WHERE id = {0}", from), conn, tran)) using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { balance = reader.GetInt32(0); } else { throw new DataException(String.Format("Account id={0} not found", from)); } } if (balance < amount) { throw new DataException(String.Format("Insufficient balance in account id={0}", from)); } using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance - {0} where id = {1}", amount, from), conn, tran)) { cmd.ExecuteNonQuery(); } using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance + {0} where id = {1}", amount, to), conn, tran)) { cmd.ExecuteNonQuery(); } } static void TxnSample(string connString) { using (var conn = new NpgsqlConnection(connString)) { conn.Open(); // Create the "accounts" table. new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery(); // Insert two rows into the "accounts" table. using (var cmd = new NpgsqlCommand()) { cmd.Connection = conn; cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)"; cmd.Parameters.AddWithValue("id1", 1); cmd.Parameters.AddWithValue("val1", 1000); cmd.Parameters.AddWithValue("id2", 2); cmd.Parameters.AddWithValue("val2", 250); cmd.ExecuteNonQuery(); } // Print out the balances. System.Console.WriteLine("Initial balances:"); using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) using (var reader = cmd.ExecuteReader()) while (reader.Read()) Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); try { using (var tran = conn.BeginTransaction()) { tran.Save("cockroach_restart"); while (true) { try { TransferFunds(conn, tran, 1, 2, 100); tran.Commit(); break; } catch (NpgsqlException e) { // Check if the error code indicates a SERIALIZATION_FAILURE. if (e.ErrorCode == 40001) { // Signal the database that we will attempt a retry. tran.Rollback("cockroach_restart"); } else { throw; } } } } } catch (DataException e) { Console.WriteLine(e.Message); } // Now printout the results. Console.WriteLine("Final balances:"); using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn)) using (var reader = cmd.ExecuteReader()) while (reader.Read()) Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1)); } } } } ``` #### Run the transactions example This time, running the code will execute a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} dotnet run ``` The output should be: ``` Initial balances: account 1: 1000 account 2: 250 Final balances: account 1: 900 account 2: 350 ``` However, if you want to verify that funds were transferred from one account to another, use the [built-in SQL client](/docs/v26.4/cockroach-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT id, balance FROM accounts; ``` ``` id | balance +----+---------+ 1 | 900 2 | 350 (2 rows) ``` ## What's next? Read more about using the [.NET Npgsql driver](http://www.npgsql.org/). You might also be interested in the following pages: * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Connection Pooling](/docs/v26.4/connection-pooling) * [Data Replication](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) # Build a Simple CRUD Go App with CockroachDB and the Go pgx Driver Source: https://docs.cockroachlabs.com/docs/stable/build-a-go-app-with-cockroachdb This tutorial shows you how build a simple CRUD Go application with CockroachDB and the [Go pgx driver](https://pkg.go.dev/github.com/jackc/pgx). ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_go_pgx). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-go-pgx/ ``` The project has the following directory structure: ``` ├── README.md └── main.go ``` The `main.go` file contains the code for `CREATE TABLE`, `INSERT`, `SELECT`, `UPDATE`, and `DELETE` SQL operations. The file also executes the `main` method of the program. ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package main "context" "log" "os" "github.com/cockroachdb/cockroach-go/v2/crdb/crdbpgxv5" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) func initTable(ctx context.Context, tx pgx.Tx) error { // Dropping existing table if it exists log.Println("Drop existing accounts table if necessary.") if _, err := tx.Exec(ctx, "DROP TABLE IF EXISTS accounts"); err != nil { return err } // Create the accounts table log.Println("Creating accounts table.") if _, err := tx.Exec(ctx, "CREATE TABLE accounts (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), balance INT8)"); err != nil { return err } return nil } func insertRows(ctx context.Context, tx pgx.Tx, accts [4]uuid.UUID) error { // Insert four rows into the "accounts" table. log.Println("Creating new rows...") if _, err := tx.Exec(ctx, "INSERT INTO accounts (id, balance) VALUES ($1, $2), ($3, $4), ($5, $6), ($7, $8)", accts[0], 250, accts[1], 100, accts[2], 500, accts[3], 300); err != nil { return err } return nil } func printBalances(conn *pgx.Conn) error { rows, err := conn.Query(context.Background(), "SELECT id, balance FROM accounts") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id uuid.UUID var balance int if err := rows.Scan(&id, &balance); err != nil { log.Fatal(err) } log.Printf("%s: %d\n", id, balance) } return nil } func transferFunds(ctx context.Context, tx pgx.Tx, from uuid.UUID, to uuid.UUID, amount int) error { // Read the balance. var fromBalance int if err := tx.QueryRow(ctx, "SELECT balance FROM accounts WHERE id = $1", from).Scan(&fromBalance); err != nil { return err } if fromBalance < amount { log.Println("insufficient funds") } // Perform the transfer. log.Printf("Transferring funds from account with ID %s to account with ID %s...", from, to) if _, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, from); err != nil { return err } if _, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance + $1 WHERE id = $2", amount, to); err != nil { return err } return nil } func deleteRows(ctx context.Context, tx pgx.Tx, one uuid.UUID, two uuid.UUID) error { // Delete two rows into the "accounts" table. log.Printf("Deleting rows with IDs %s and %s...", one, two) if _, err := tx.Exec(ctx, "DELETE FROM accounts WHERE id IN ($1, $2)", one, two); err != nil { return err } return nil } func main() { // Read in connection string config, err := pgx.ParseConfig(os.Getenv("DATABASE_URL")) if err != nil { log.Fatal(err) } config.RuntimeParams["application_name"] = "$ docs_simplecrud_gopgx" conn, err := pgx.ConnectConfig(context.Background(), config) if err != nil { log.Fatal(err) } defer conn.Close(context.Background()) // Set up table err = crdbpgx.ExecuteTx(context.Background(), conn, pgx.TxOptions{}, func(tx pgx.Tx) error { return initTable(context.Background(), tx) }) // Insert initial rows var accounts [4]uuid.UUID for i := 0; i < len(accounts); i++ { accounts[i] = uuid.New() } err = crdbpgx.ExecuteTx(context.Background(), conn, pgx.TxOptions{}, func(tx pgx.Tx) error { return insertRows(context.Background(), tx, accounts) }) if err == nil { log.Println("New rows created.") } else { log.Fatal("error: ", err) } // Print out the balances log.Println("Initial balances:") printBalances(conn) // Run a transfer err = crdbpgx.ExecuteTx(context.Background(), conn, pgx.TxOptions{}, func(tx pgx.Tx) error { return transferFunds(context.Background(), tx, accounts[2], accounts[1], 100) }) if err == nil { log.Println("Transfer successful.") } else { log.Fatal("error: ", err) } // Print out the balances log.Println("Balances after transfer:") printBalances(conn) // Delete rows err = crdbpgx.ExecuteTx(context.Background(), conn, pgx.TxOptions{}, func(tx pgx.Tx) error { return deleteRows(context.Background(), tx, accounts[0], accounts[1]) }) if err == nil { log.Println("Rows deleted.") } else { log.Fatal("error: ", err) } // Print out the balances log.Println("Balances after deletion:") printBalances(conn) } ``` > [!NOTE] > > CockroachDB may require the [client to retry a transaction](/docs/v26.4/transactions#transaction-retries) in the case of read/write [contention](/docs/v26.4/performance-best-practices-overview#transaction-contention). The [CockroachDB Go client](https://github.com/cockroachdb/cockroach-go) includes a generic **retry function** (`ExecuteTx()`) that runs inside a transaction and retries it as needed. The code sample shows how you can use this function to wrap SQL statements. ## Step 3. Initialize the database 1. Navigate to the `example-app-go-pgx` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-go-pgx ``` 2. Set the `DATABASE_URL` environment variable to the connection string for your cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="{connection-string}" ``` Where `{connection-string}` is the connection string you copied earlier. ## Step 4. Run the code 1. Initialize the module: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go mod tidy ``` 2. Run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go run main.go ``` The output should look similar to the following: ``` 2023/03/24 13:48:13 Drop existing accounts table if necessary. 2023/03/24 13:48:13 Creating accounts table. 2023/03/24 13:48:13 Creating new rows... 2023/03/24 13:48:13 New rows created. 2023/03/24 13:48:13 Initial balances: 2023/03/24 13:48:13 19a2b534-11f6-4bbd-ab50-b94c44479280: 500 2023/03/24 13:48:13 882bb8be-31cb-4481-8e28-69b0566a322b: 300 2023/03/24 13:48:13 b8cbefed-37ee-4bae-b5b0-3bcfb7a6d3bf: 250 2023/03/24 13:48:13 d0a238d5-96bd-42d7-89a3-3e2448b3137b: 100 2023/03/24 13:48:14 Transferring funds from account with ID 19a2b534-11f6-4bbd-ab50-b94c44479280 to account with ID d0a238d5-96bd-42d7-89a3-3e2448b3137b... 2023/03/24 13:48:14 Transfer successful. 2023/03/24 13:48:14 Balances after transfer: 2023/03/24 13:48:14 19a2b534-11f6-4bbd-ab50-b94c44479280: 400 2023/03/24 13:48:14 882bb8be-31cb-4481-8e28-69b0566a322b: 300 2023/03/24 13:48:14 b8cbefed-37ee-4bae-b5b0-3bcfb7a6d3bf: 250 2023/03/24 13:48:14 d0a238d5-96bd-42d7-89a3-3e2448b3137b: 200 2023/03/24 13:48:14 Deleting rows with IDs b8cbefed-37ee-4bae-b5b0-3bcfb7a6d3bf and d0a238d5-96bd-42d7-89a3-3e2448b3137b... 2023/03/24 13:48:14 Rows deleted. 2023/03/24 13:48:14 Balances after deletion: 2023/03/24 13:48:14 19a2b534-11f6-4bbd-ab50-b94c44479280: 400 2023/03/24 13:48:14 882bb8be-31cb-4481-8e28-69b0566a322b: 300 ``` As shown in the output, the code does the following: * Drops any existing `accounts` table. * Creates a new `accounts` table. * Inserts some rows into the table. * Reads values from the table. * Updates values in the table. * Deletes values from the table. ## What's next? Read more about using the [Go pgx driver](https://pkg.go.dev/github.com/jackc/pgx?tab=doc). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Go App with CockroachDB and GORM Source: https://docs.cockroachlabs.com/docs/stable/build-a-go-app-with-cockroachdb-gorm This tutorial shows you how build a simple CRUD Go application with CockroachDB and the [GORM ORM](https://gorm.io/index.html). > [!TIP] > > For another use of GORM with CockroachDB, see our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_go_gorm). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-go-gorm ``` The project has the following directory structure: ``` ├── README.md └── main.go ``` The `main.go` file defines an `Account` struct that maps to a new `accounts` table. The file also contains some read and write database operations that are executed in the `main` method of the program. ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package main "context" "fmt" "log" "math/rand" "os" "time" "github.com/cockroachdb/cockroach-go/v2/crdb/crdbgorm" "github.com/google/uuid" "gorm.io/driver/postgres" "gorm.io/gorm" ) // Account is our model, which corresponds to the "accounts" table type Account struct { ID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"` Balance int } // The `acctIDs` global variable tracks the random IDs generated by `addAccounts` var acctIDs []uuid.UUID // Insert new rows into the "accounts" table // This function generates new UUIDs and random balances for each row, and // then it appends the ID to the `acctIDs`, which other functions use to track the IDs func addAccounts(db *gorm.DB, numRows int, transferAmount int) error { log.Printf("Creating %d new accounts...", numRows) for i := 0; i < numRows; i++ { newID := uuid.New() newBalance := rand.Intn(10000) + transferAmount if err := db.Create(&Account{ID: newID, Balance: newBalance}).Error; err != nil { return err } acctIDs = append(acctIDs, newID) } log.Println("Accounts created.") return nil } // Transfer funds between accounts // This function adds `amount` to the "balance" column of the row with the "id" column matching `toID`, // and removes `amount` from the "balance" column of the row with the "id" column matching `fromID` func transferFunds(db *gorm.DB, fromID uuid.UUID, toID uuid.UUID, amount int) error { log.Printf("Transferring %d from account %s to account %s...", amount, fromID, toID) var fromAccount Account var toAccount Account db.First(&fromAccount, fromID) db.First(&toAccount, toID) if fromAccount.Balance < amount { return fmt.Errorf("account %s balance %d is lower than transfer amount %d", fromAccount.ID, fromAccount.Balance, amount) } fromAccount.Balance -= amount toAccount.Balance += amount if err := db.Save(&fromAccount).Error; err != nil { return err } if err := db.Save(&toAccount).Error; err != nil { return err } log.Println("Funds transferred.") return nil } // Print IDs and balances for all rows in "accounts" table func printBalances(db *gorm.DB) { var accounts []Account db.Find(&accounts) fmt.Printf("Balance at '%s':\n", time.Now()) for _, account := range accounts { fmt.Printf("%s %d\n", account.ID, account.Balance) } } // Delete all rows in "accounts" table inserted by `main` (i.e., tracked by `acctIDs`) func deleteAccounts(db *gorm.DB, accountIDs []uuid.UUID) error { log.Println("Deleting accounts created...") err := db.Where("id IN ?", accountIDs).Delete(Account{}).Error if err != nil { return err } log.Println("Accounts deleted.") return nil } func main() { db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")+"&application_name=$ docs_simplecrud_gorm"), &gorm.Config{}) if err != nil { log.Fatal(err) } // Automatically create the "accounts" table based on the `Account` // model. db.AutoMigrate(&Account{}) // The number of initial rows to insert const numAccts int = 5 // The amount to be transferred between two accounts. const transferAmt int = 100 // Insert `numAccts` rows into the "accounts" table. // To handle potential transaction retry errors, we wrap the call // to `addAccounts` in `crdbgorm.ExecuteTx`, a helper function for // GORM which implements a retry loop if err := crdbgorm.ExecuteTx(context.Background(), db, nil, func(tx *gorm.DB) error { return addAccounts(db, numAccts, transferAmt) }, ); err != nil { // For information and reference documentation, see: // https://www.cockroachlabs.com/docs/stable/error-handling-and-troubleshooting.html fmt.Println(err) } // Print balances before transfer. printBalances(db) // Select two account IDs fromID := acctIDs[0] toID := acctIDs[0:][rand.Intn(len(acctIDs))] // Transfer funds between accounts. To handle potential // transaction retry errors, we wrap the call to `transferFunds` // in `crdbgorm.ExecuteTx` if err := crdbgorm.ExecuteTx(context.Background(), db, nil, func(tx *gorm.DB) error { return transferFunds(tx, fromID, toID, transferAmt) }, ); err != nil { // For information and reference documentation, see: // https://www.cockroachlabs.com/docs/stable/error-handling-and-troubleshooting.html fmt.Println(err) } // Print balances after transfer to ensure that it worked. printBalances(db) // Delete all accounts created by the earlier call to `addAccounts` // To handle potential transaction retry errors, we wrap the call // to `deleteAccounts` in `crdbgorm.ExecuteTx` if err := crdbgorm.ExecuteTx(context.Background(), db, nil, func(tx *gorm.DB) error { return deleteAccounts(db, acctIDs) }, ); err != nil { // For information and reference documentation, see: // https://www.cockroachlabs.com/docs/stable/error-handling-and-troubleshooting.html fmt.Println(err) } } ``` > [!NOTE] > > CockroachDB may require the [client to retry a transaction](/docs/v26.4/transactions#transaction-retries) in the case of read/write [contention](/docs/v26.4/performance-best-practices-overview#transaction-contention). The [CockroachDB Go client](https://github.com/cockroachdb/cockroach-go) includes a generic **retry function** (`ExecuteTx()`) that runs inside a transaction and retries it as needed. The code sample shows how you can use this function to wrap SQL statements. ## Step 3. Initialize the database 1. Navigate to the `example-app-go-gorm` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-go-gorm ``` 2. Set the `DATABASE_URL` environment variable to the connection string for your cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="{connection-string}" ``` Where `{connection-string}` is the connection string you copied earlier. ## Step 4. Run the code 1. Initialize the module: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-go-gorm ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go mod init basic-sample && go mod tidy ``` 2. Run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go run main.go ``` The output should look similar to the following: ``` 2021/09/16 14:17:12 Creating 5 new accounts... 2021/09/16 14:17:12 Accounts created. Balance at '2021-09-16 14:17:12.68843 -0400 EDT m=+2.760587790': 1580d2f4-c9ec-4f26-bbe7-6a53e9aa5170 1947 26ddc77b-8068-409b-b305-0c5d873f7c43 7987 3d97ea5a-5108-4388-88e8-92524d5de5e8 4159 af49831d-d637-4a20-a9a7-01e9fe4628fe 8181 f0cc97ef-e3fe-4abb-a44a-0dd04207f7d4 2181 2021/09/16 14:17:12 Transferring 100 from account af49831d-d637-4a20-a9a7-01e9fe4628fe to account 3d97ea5a-5108-4388-88e8-92524d5de5e8... 2021/09/16 14:17:12 Funds transferred. Balance at '2021-09-16 14:17:12.759686 -0400 EDT m=+2.831841311': 1580d2f4-c9ec-4f26-bbe7-6a53e9aa5170 1947 26ddc77b-8068-409b-b305-0c5d873f7c43 7987 3d97ea5a-5108-4388-88e8-92524d5de5e8 4259 af49831d-d637-4a20-a9a7-01e9fe4628fe 8081 f0cc97ef-e3fe-4abb-a44a-0dd04207f7d4 2181 2021/09/16 14:17:12 Deleting accounts created... 2021/09/16 14:17:12 Accounts deleted. ``` The code runs a migration that creates the `accounts` table in the `bank` database, based on the `Account` struct defined at the top of the `main.go` file. As shown in the output, the code also does the following: * Inserts some rows into the `accounts` table. * Reads values from the table. * Updates values in the table. * Deletes values from the table. ## What's next? Read more about using the [GORM ORM](http://gorm.io), or check out a more realistic implementation of GORM with CockroachDB in our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Go App with CockroachDB the Go pq Driver Source: https://docs.cockroachlabs.com/docs/stable/build-a-go-app-with-cockroachdb-pq This tutorial shows you how build a simple Go application with CockroachDB and the Go [pq driver](https://github.com/lib/pq). ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_go_pq). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/hello-world-go-pq ``` ## Step 3. Initialize the database 1. Navigate to the `hello-world-go-pq` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd hello-world-go-pq ``` 2. Set the `DATABASE_URL` environment variable to the connection string for your cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="{connection-string}" ``` Where `{connection-string}` is the connection string you copied earlier. ## Step 4. Run the code You can now run the code sample (`main.go`) provided in this tutorial to do the following: * Create a table. * Insert some rows into the table you created. * Read values from the table. * Execute a batch of statements as an atomic [transaction](/docs/v26.4/transactions). Note that CockroachDB may require the [client to retry a transaction](/docs/v26.4/transactions#transaction-retries) in the case of read/write [contention](/docs/v26.4/performance-best-practices-overview#transaction-contention). The [CockroachDB Go client](https://github.com/cockroachdb/cockroach-go) includes a generic **retry function** (`ExecuteTx()`) that runs inside a transaction and retries it as needed. The code sample shows how you can use this function to wrap SQL statements. 1. Initialize the module: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go mod init basic-sample && go mod tidy ``` 2. Run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go run main.go ``` The output should be: ``` Balances: 1 1000 2 250 Success Balances: 1 900 2 350 ``` ## What's next? Read more about using the [Go pq driver](https://godoc.org/github.com/lib/pq). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Go App with CockroachDB and upper/db Source: https://docs.cockroachlabs.com/docs/stable/build-a-go-app-with-cockroachdb-upperdb This tutorial shows you how build a simple Go application with CockroachDB and the [upper/db](https://upper.io/) data access layer. ## Before you begin 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac). 2. Start up a [secure](/docs/v26.4/secure-a-cluster) or [insecure](/docs/v26.4/start-a-local-cluster) local cluster. 3. Choose the instructions that correspond to whether your cluster is secure or insecure: > [!CAUTION] > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. > [tab] Secure > > ## Step 1. Create the `maxroach` user and `bank` database > > Start the [built-in SQL shell](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --certs-dir=certs > ``` > > In the SQL shell, issue the following statements to create the `maxroach` user and `bank` database: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER IF NOT EXISTS maxroach; > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > Give the `maxroach` user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO maxroach; > ``` > > Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > > ## Step 2. Generate a certificate for the `maxroach` user > > Create a certificate and key for the `maxroach` user by running the following command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach cert create-client maxroach --certs-dir=certs --ca-key=my-safe-directory/ca.key > ``` > > The code samples will run with `maxroach` as the user. > > ## Step 3. Run the Go code > > The sample code shown below uses upper/db to map Go-specific objects to SQL operations. Specifically, the code: > > * Creates the `accounts` table, if it does not already exist. > * Deletes any existing rows in the `accounts` table. > * Inserts two rows into the `accounts` table. > * Prints the rows in the `accounts` table to the terminal. > * Deletes the first row in the `accounts` table. > * Updates the rows in the `accounts` table within an explicit [transaction](/docs/v26.4/transactions). > * Prints the rows in the `accounts` table to the terminal once more. > > ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > package main > > "fmt" > "log" > "time" > > "github.com/upper/db/v4" > "github.com/upper/db/v4/adapter/cockroachdb" > ) > > // The settings variable stores connection details. > var settings = cockroachdb.ConnectionURL{ > Host: "localhost", > Database: "bank", > User: "maxroach", > Options: map[string]string{ > // Secure node. > "sslrootcert": "certs/ca.crt", > "sslkey": "certs/client.maxroach.key", > "sslcert": "certs/client.maxroach.crt", > }, > } > > // Accounts is a handy way to represent a collection. > func Accounts(sess db.Session) db.Store { > return sess.Collection("accounts") > } > > // Account is used to represent a single record in the "accounts" table. > type Account struct { > ID uint64 `db:"id,omitempty"` > Balance int64 `db:"balance"` > } > > // Collection is required in order to create a relation between the Account > // struct and the "accounts" table. > func (a *Account) Store(sess db.Session) db.Store { > return Accounts(sess) > } > > // createTables creates all the tables that are neccessary to run this example. > func createTables(sess db.Session) error { > _, err := sess.SQL().Exec(` > CREATE TABLE IF NOT EXISTS accounts ( > ID SERIAL PRIMARY KEY, > balance INT > ) > `) > if err != nil { > return err > } > return nil > } > > // crdbForceRetry can be used to simulate a transaction error and > // demonstrate upper/db's ability to retry the transaction automatically. > // > // By default, upper/db will retry the transaction five times, if you want > // to modify this number use: sess.SetMaxTransactionRetries(n). > // > // This is only used for demonstration purposes and not intended > // for production code. > func crdbForceRetry(sess db.Session) error { > var err error > > // The first statement in a transaction can be retried transparently on the > // server, so we need to add a placeholder statement so that our > // force_retry() statement isn't the first one. > _, err = sess.SQL().Exec(`SELECT 1`) > if err != nil { > return err > } > > // If force_retry is called during the specified interval from the beginning > // of the transaction it returns a retryable error. If not, 0 is returned > // instead of an error. > _, err = sess.SQL().Exec(`SELECT crdb_internal.force_retry('1s'::INTERVAL)`) > if err != nil { > return err > } > > return nil > } > > func main() { > // Connect to the local CockroachDB node. > sess, err := cockroachdb.Open(settings) > if err != nil { > log.Fatal("cockroachdb.Open: ", err) > } > defer sess.Close() > > // Adjust this number to fit your specific needs (set to 5, by default) > // sess.SetMaxTransactionRetries(10) > > // Create the "accounts" table > createTables(sess) > > // Delete all the previous items in the "accounts" table. > err = Accounts(sess).Truncate() > if err != nil { > log.Fatal("Truncate: ", err) > } > > // Create a new account with a balance of 1000. > account1 := Account{Balance: 1000} > err = Accounts(sess).InsertReturning(&account1) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Create a new account with a balance of 250. > account2 := Account{Balance: 250} > err = Accounts(sess).InsertReturning(&account2) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Printing records > printRecords(sess) > > // Change the balance of the first account. > account1.Balance = 500 > err = sess.Save(&account1) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Change the balance of the second account. > account2.Balance = 999 > err = sess.Save(&account2) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Printing records > printRecords(sess) > > // Delete the first record. > err = sess.Delete(&account1) > if err != nil { > log.Fatal("Delete: ", err) > } > > startTime := time.Now() > > // Add a couple of new records within a transaction. > err = sess.Tx(func(tx db.Session) error { > var err error > > if err = tx.Save(&Account{Balance: 887}); err != nil { > return err > } > > if time.Now().Sub(startTime) < time.Second*1 { > // Will fail continuously for 2 seconds. > if err = crdbForceRetry(tx); err != nil { > return err > } > } > > if err = tx.Save(&Account{Balance: 342}); err != nil { > return err > } > > return nil > }) > if err != nil { > log.Fatal("Could not commit transaction: ", err) > } > > // Printing records > printRecords(sess) > } > > func printRecords(sess db.Session) { > accounts := []Account{} > err := Accounts(sess).Find().All(&accounts) > if err != nil { > log.Fatal("Find: ", err) > } > log.Printf("Balances:") > for i := range accounts { > fmt.Printf("\taccounts[%d]: %d\n", accounts[i].ID, accounts[i].Balance) > } > } > ``` > > Note that the sample code also includes a function that simulates a transaction error (`crdbForceRetry()`). Upper/db's CockroachDB adapter [automatically retries transactions](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling) when transaction errors are thrown. As a result, this function forces a transaction retry. > > To run the code, copy the sample above, or download it directly. > > > [!TIP] > > > > To clone a version of the code below that connects to insecure clusters, run the following command: > > > > `git clone https://github.com/cockroachlabs/hello-world-go-upperdb/` > > > > Note that you will need to edit the connection string to use the certificates that you generated when you set up your secure cluster. > [tab] Insecure > > ## Step 1. Create the `maxroach` user and `bank` database > > Start the [built-in SQL shell](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --insecure > ``` > > In the SQL shell, issue the following statements to create the `maxroach` user and `bank` database: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER IF NOT EXISTS maxroach; > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > Give the `maxroach` user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO maxroach; > ``` > > Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > > ## Step 2. Run the Go code > > The sample code shown below uses upper/db to map Go-specific objects to SQL operations. Specifically, the code: > > * Creates the `accounts` table, if it does not already exist. > * Deletes any existing rows in the `accounts` table. > * Inserts two rows into the `accounts` table. > * Prints the rows in the `accounts` table to the terminal. > * Deletes the first row in the `accounts` table. > * Updates the rows in the `accounts` table within an explicit [transaction](/docs/v26.4/transactions). > * Prints the rows in the `accounts` table to the terminal once more. > > ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > package main > > "fmt" > "log" > "time" > > "github.com/upper/db/v4" > "github.com/upper/db/v4/adapter/cockroachdb" > ) > > // The settings variable stores connection details. > var settings = cockroachdb.ConnectionURL{ > Host: "localhost", > Database: "bank", > User: "maxroach", > Options: map[string]string{ > // Insecure node. > "sslmode": "disable", > }, > } > > // Accounts is a handy way to represent a collection. > func Accounts(sess db.Session) db.Store { > return sess.Collection("accounts") > } > > // Account is used to represent a single record in the "accounts" table. > type Account struct { > ID uint64 `db:"id,omitempty"` > Balance int64 `db:"balance"` > } > > // Collection is required in order to create a relation between the Account > // struct and the "accounts" table. > func (a *Account) Store(sess db.Session) db.Store { > return Accounts(sess) > } > > // createTables creates all the tables that are neccessary to run this example. > func createTables(sess db.Session) error { > _, err := sess.SQL().Exec(` > CREATE TABLE IF NOT EXISTS accounts ( > ID SERIAL PRIMARY KEY, > balance INT > ) > `) > if err != nil { > return err > } > return nil > } > > // crdbForceRetry can be used to simulate a transaction error and > // demonstrate upper/db's ability to retry the transaction automatically. > // > // By default, upper/db will retry the transaction five times, if you want > // to modify this number use: sess.SetMaxTransactionRetries(n). > // > // This is only used for demonstration purposes and not intended > // for production code. > func crdbForceRetry(sess db.Session) error { > var err error > > // The first statement in a transaction can be retried transparently on the > // server, so we need to add a placeholder statement so that our > // force_retry() statement isn't the first one. > _, err = sess.SQL().Exec(`SELECT 1`) > if err != nil { > return err > } > > // If force_retry is called during the specified interval from the beginning > // of the transaction it returns a retryable error. If not, 0 is returned > // instead of an error. > _, err = sess.SQL().Exec(`SELECT crdb_internal.force_retry('1s'::INTERVAL)`) > if err != nil { > return err > } > > return nil > } > > func main() { > // Connect to the local CockroachDB node. > sess, err := cockroachdb.Open(settings) > if err != nil { > log.Fatal("cockroachdb.Open: ", err) > } > defer sess.Close() > > // Adjust this number to fit your specific needs (set to 5, by default) > // sess.SetMaxTransactionRetries(10) > > // Create the "accounts" table > createTables(sess) > > // Delete all the previous items in the "accounts" table. > err = Accounts(sess).Truncate() > if err != nil { > log.Fatal("Truncate: ", err) > } > > // Create a new account with a balance of 1000. > account1 := Account{Balance: 1000} > err = Accounts(sess).InsertReturning(&account1) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Create a new account with a balance of 250. > account2 := Account{Balance: 250} > err = Accounts(sess).InsertReturning(&account2) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Printing records > printRecords(sess) > > // Change the balance of the first account. > account1.Balance = 500 > err = sess.Save(&account1) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Change the balance of the second account. > account2.Balance = 999 > err = sess.Save(&account2) > if err != nil { > log.Fatal("sess.Save: ", err) > } > > // Printing records > printRecords(sess) > > // Delete the first record. > err = sess.Delete(&account1) > if err != nil { > log.Fatal("Delete: ", err) > } > > startTime := time.Now() > > // Add a couple of new records within a transaction. > err = sess.Tx(func(tx db.Session) error { > var err error > > if err = tx.Save(&Account{Balance: 887}); err != nil { > return err > } > > if time.Now().Sub(startTime) < time.Second*1 { > // Will fail continuously for 2 seconds. > if err = crdbForceRetry(tx); err != nil { > return err > } > } > > if err = tx.Save(&Account{Balance: 342}); err != nil { > return err > } > > return nil > }) > if err != nil { > log.Fatal("Could not commit transaction: ", err) > } > > // Printing records > printRecords(sess) > } > > func printRecords(sess db.Session) { > accounts := []Account{} > err := Accounts(sess).Find().All(&accounts) > if err != nil { > log.Fatal("Find: ", err) > } > log.Printf("Balances:") > for i := range accounts { > fmt.Printf("\taccounts[%d]: %d\n", accounts[i].ID, accounts[i].Balance) > } > } > ``` > > Note that the sample code also includes a function that simulates a transaction error (`crdbForceRetry()`). Upper/db's CockroachDB adapter [automatically retries transactions](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling) when transaction errors are thrown. As a result, this function forces a transaction retry. > > Copy the code or download it directly. > > To clone a version of the code below that connects to insecure clusters, run the following command: > > `git clone https://github.com/cockroachlabs/hello-world-go-upperdb/` Change to the directory where you cloned the repo and get the dependencies with `go mod init`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go mod init hello-world-go-upperdb ``` Then run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ go run main.go ``` The output should look similar to the following: ``` go: finding module for package github.com/upper/db/v4 go: finding module for package github.com/upper/db/v4/adapter/cockroachdb go: found github.com/upper/db/v4 in github.com/upper/db/v4 v4.0.0 2020/09/16 10:31:55 Balances: accounts[590467288222990337]: 1000 accounts[590467288229576705]: 250 2020/09/16 10:31:55 Balances: accounts[590467288222990337]: 500 accounts[590467288229576705]: 999 2020/09/16 10:31:55 upper/db: log_level=WARNING file=go/pkg/mod/github.com/upper/db/v4@v4.0.0/internal/sqladapter/session.go:642 Session ID: 00006 Transaction ID: 00005 Query: SELECT crdb_internal.force_retry('1ms'::INTERVAL) Error: pq: restart transaction: crdb_internal.force_retry(): TransactionRetryWithProtoRefreshError: forced by crdb_internal.force_retry() Time taken: 0.00171s Context: context.Background 2020/09/16 10:31:55 upper/db: log_level=WARNING file=go/pkg/mod/github.com/upper/db/v4@v4.0.0/internal/sqladapter/session.go:642 Session ID: 00006 Transaction ID: 00005 Query: INSERT INTO "accounts" ("balance") VALUES ($1) RETURNING "id" Arguments: []interface {}{887} Error: pq: current transaction is aborted, commands ignored until end of transaction block Time taken: 0.00065s Context: context.Background 2020/09/16 10:31:56 Balances: accounts[590467288229576705]: 999 accounts[590467288342757377]: 887 accounts[590467288350064641]: 342 ``` Note that the forced transaction errors result in errors printed to the terminal, but the transactions are retried until they succeed. ## What's next? Read more about upper/db: * [Introduction to upper/db](https://upper.io/v4/getting-started/) * [The upper/db tour](https://tour.upper.io/) * [upper/db reference docs](https://pkg.go.dev/github.com/upper/db/v4) You might also be interested in the following pages: * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Connection Pooling](/docs/v26.4/connection-pooling) * [Data Replication](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) # Build a Simple CRUD Java App with CockroachDB and JDBC Source: https://docs.cockroachlabs.com/docs/stable/build-a-java-app-with-cockroachdb This tutorial shows you how to build a simple CRUD Java application with CockroachDB and the Java JDBC driver. > [!NOTE] > > We recommend using Java versions 8+ with CockroachDB. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_java_jdbc). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **Java** from the **Select option/language** dropdown. > > > > 2. Select **JDBC** from the **Select tool** dropdown. > > > > 3. Copy the command provided to set the `JDBC_DATABASE_URL` environment variable. > > > > > [!NOTE] > > > > > > The JDBC connection URL is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} git clone https://github.com/cockroachlabs/example-app-java-jdbc/ ``` The project has the following directory structure: ``` ├── README.md ├── app │   ├── build.gradle │   └── src │   └── main │   ├── java │   │   └── com │   │   └── cockroachlabs │   │   └── BasicExample.java ├── gradle │   └── wrapper │   ├── gradle-wrapper.jar │   └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ``` The `BasicExample.java` file contains the code for `INSERT`, `SELECT`, and `UPDATE` SQL operations. The file also contains the `main` method of the program. ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.cockroachlabs; /** * Main class for the basic JDBC example. **/ public class BasicExample { public static void main(String[] args) { // Configure the database connection. PGSimpleDataSource ds = new PGSimpleDataSource(); ds.setApplicationName("docs_simplecrud_jdbc"); ds.setUrl(System.getenv("JDBC_DATABASE_URL")); // Create DAO. BasicExampleDAO dao = new BasicExampleDAO(ds); // Test our retry handling logic if FORCE_RETRY is true. This // method is only used to test the retry logic. It is not // necessary in production code. dao.testRetryHandling(); // Create the accounts table if it doesn't exist dao.createAccountsTable(); // Insert a few accounts "by hand", using INSERTs on the backend. Map balances = new HashMap<>(); UUID id1 = UUID.randomUUID(); UUID id2 = UUID.randomUUID(); balances.put(id1.toString(), "1000"); balances.put(id2.toString(), "250"); int updatedAccounts = dao.updateAccounts(balances); System.out.printf("BasicExampleDAO.updateAccounts:\n => %s total updated accounts\n", updatedAccounts); // How much money is in these accounts? BigDecimal balance1 = dao.getAccountBalance(id1); BigDecimal balance2 = dao.getAccountBalance(id2); System.out.printf("main:\n => Account balances at time '%s':\n ID %s => $%s\n ID %s => $%s\n", LocalTime.now(), 1, balance1, 2, balance2); // Transfer $100 from account 1 to account 2 UUID fromAccount = UUID.randomUUID(); UUID toAccount = UUID.randomUUID(); BigDecimal transferAmount = BigDecimal.valueOf(100); int transferredAccounts = dao.transferFunds(fromAccount, toAccount, transferAmount); if (transferredAccounts != -1) { System.out.printf("BasicExampleDAO.transferFunds:\n => $%s transferred between accounts %s and %s, %s rows updated\n", transferAmount, fromAccount, toAccount, transferredAccounts); } balance1 = dao.getAccountBalance(id1); balance2 = dao.getAccountBalance(id2); System.out.printf("main:\n => Account balances at time '%s':\n ID %s => $%s\n ID %s => $%s\n", LocalTime.now(), 1, balance1, 2, balance2); // Bulk insertion example using JDBC's batching support. int totalRowsInserted = dao.bulkInsertRandomAccountData(); System.out.printf("\nBasicExampleDAO.bulkInsertRandomAccountData:\n => finished, %s total rows inserted\n", totalRowsInserted); // Print out 10 account values. int accountsRead = dao.readAccounts(10); } } /** * Data access object used by 'BasicExample'. Abstraction over some * common CockroachDB operations, including: * * - Auto-handling transaction retries in the 'runSQL' method * * - Example of bulk inserts in the 'bulkInsertRandomAccountData' * method */ class BasicExampleDAO { private static final int MAX_RETRY_COUNT = 3; private static final String RETRY_SQL_STATE = "40001"; private static final boolean FORCE_RETRY = false; private final DataSource ds; private final Random rand = new Random(); BasicExampleDAO(DataSource ds) { this.ds = ds; } /** Used to test the retry logic in 'runSQL'. It is not necessary in production code. */ void testRetryHandling() { if (BasicExampleDAO.FORCE_RETRY) { runSQL("SELECT crdb_internal.force_retry('1s':::INTERVAL)"); } } /** * Run SQL code in a way that automatically handles the * transaction retry logic so we don't have to duplicate it in * various places. * * @param sqlCode a String containing the SQL code you want to * execute. Can have placeholders, e.g., "INSERT INTO accounts * (id, balance) VALUES (?, ?)". * * @param args String Varargs to fill in the SQL code's * placeholders. * @return Integer Number of rows updated, or -1 if an error is thrown. */ public Integer runSQL(String sqlCode, String... args) { // This block is only used to emit class and method names in // the program output. It is not necessary in production // code. StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement elem = stacktrace[2]; String callerClass = elem.getClassName(); String callerMethod = elem.getMethodName(); int rv = 0; try (Connection connection = ds.getConnection()) { // We're managing the commit lifecycle ourselves so we can // automatically issue transaction retries. connection.setAutoCommit(false); int retryCount = 0; while (retryCount <= MAX_RETRY_COUNT) { if (retryCount == MAX_RETRY_COUNT) { String err = String.format("hit max of %s retries, aborting", MAX_RETRY_COUNT); throw new RuntimeException(err); } // This block is only used to test the retry logic. // It is not necessary in production code. See also // the method 'testRetryHandling()'. if (FORCE_RETRY) { forceRetry(connection); // SELECT 1 } try (PreparedStatement pstmt = connection.prepareStatement(sqlCode)) { // Loop over the args and insert them into the // prepared statement based on their types. In // this simple example we classify the argument // types as "integers" and "everything else" // (a.k.a. strings). for (int i=0; i %s, cause => %s, message => %s }\n", e.getSQLState(), e.getCause(), e.getMessage()); rv = -1; } return rv; } /** * Helper method called by 'testRetryHandling'. It simply issues * a "SELECT 1" inside the transaction to force a retry. This is * necessary to take the connection's session out of the AutoRetry * state, since otherwise the other statements in the session will * be retried automatically, and the client (us) will not see a * retry error. Note that this information is taken from the * following test: * https://github.com/cockroachdb/cockroach/blob/master/pkg/sql/logictest/testdata/logic_test/manual_retry * * @param connection Connection */ private void forceRetry(Connection connection) throws SQLException { try (PreparedStatement statement = connection.prepareStatement("SELECT 1")){ statement.executeQuery(); } } /** * Update accounts by passing in a Map of (ID, Balance) pairs. * * @param accounts (Map) * @return The number of updated accounts (int) */ public int updateAccounts(Map accounts) { int rows = 0; for (Map.Entry account : accounts.entrySet()) { String k = account.getKey(); String v = account.getValue(); String[] args = {k, v}; rows += runSQL("INSERT INTO accounts (id, balance) VALUES (?, ?)", args); } return rows; } /** * Transfer funds between one account and another. Handles * transaction retries in case of conflict automatically on the * backend. * @param fromId (UUID) * @param toId (UUID) * @param amount (int) * @return The number of updated accounts (int) */ public int transferFunds(UUID fromId, UUID toId, BigDecimal amount) { String sFromId = fromId.toString(); String sToId = toId.toString(); String sAmount = amount.toPlainString(); // We have omitted explicit BEGIN/COMMIT statements for // brevity. Individual statements are treated as implicit // transactions by CockroachDB (see // https://www.cockroachlabs.com/docs/stable/transactions.html#individual-statements). String sqlCode = "UPSERT INTO accounts (id, balance) VALUES" + "(?, ((SELECT balance FROM accounts WHERE id = ?) - ?))," + "(?, ((SELECT balance FROM accounts WHERE id = ?) + ?))"; return runSQL(sqlCode, sFromId, sFromId, sAmount, sToId, sToId, sAmount); } /** * Get the account balance for one account. * * We skip using the retry logic in 'runSQL()' here for the * following reasons: * * 1. Since this is a single read ("SELECT"), we don't expect any * transaction conflicts to handle * * 2. We need to return the balance as an integer * * @param id (UUID) * @return balance (int) */ public BigDecimal getAccountBalance(UUID id) { BigDecimal balance = BigDecimal.valueOf(0); try (Connection connection = ds.getConnection()) { // Check the current balance. ResultSet res = connection.createStatement() .executeQuery(String.format("SELECT balance FROM accounts WHERE id = '%s'", id.toString())); if(!res.next()) { System.out.printf("No users in the table with id %d", id); } else { balance = res.getBigDecimal("balance"); } } catch (SQLException e) { System.out.printf("BasicExampleDAO.getAccountBalance ERROR: { state => %s, cause => %s, message => %s }\n", e.getSQLState(), e.getCause(), e.getMessage()); } return balance; } /** * Insert randomized account data (ID, balance) using the JDBC * fast path for bulk inserts. The fastest way to get data into * CockroachDB is the IMPORT statement. However, if you must bulk * ingest from the application using INSERT statements, the best * option is the method shown here. It will require the following: * * 1. Add `rewriteBatchedInserts=true` to your JDBC connection * settings (see the connection info in 'BasicExample.main'). * * 2. Inserting in batches of 128 rows, as used inside this method * (see BATCH_SIZE), since the PGJDBC driver's logic works best * with powers of two, such that a batch of size 128 can be 6x * faster than a batch of size 250. * @return The number of new accounts inserted (int) */ public int bulkInsertRandomAccountData() { Random random = new Random(); int BATCH_SIZE = 128; int totalNewAccounts = 0; try (Connection connection = ds.getConnection()) { // We're managing the commit lifecycle ourselves so we can // control the size of our batch inserts. connection.setAutoCommit(false); // In this example we are adding 500 rows to the database, // but it could be any number. What's important is that // the batch size is 128. try (PreparedStatement pstmt = connection.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, ?)")) { for (int i=0; i<=(500/BATCH_SIZE);i++) { for (int j=0; j %s row(s) updated in this batch\n", count.length); } connection.commit(); } catch (SQLException e) { System.out.printf("BasicExampleDAO.bulkInsertRandomAccountData ERROR: { state => %s, cause => %s, message => %s }\n", e.getSQLState(), e.getCause(), e.getMessage()); } } catch (SQLException e) { System.out.printf("BasicExampleDAO.bulkInsertRandomAccountData ERROR: { state => %s, cause => %s, message => %s }\n", e.getSQLState(), e.getCause(), e.getMessage()); } return totalNewAccounts; } /** * Read out a subset of accounts from the data store. * * @param limit (int) * @return Number of accounts read (int) */ public int readAccounts(int limit) { return runSQL("SELECT id, balance FROM accounts LIMIT ?", Integer.toString(limit)); } /** * Create the accounts table if it doesn't already exist. * */ public void createAccountsTable() { runSQL("CREATE TABLE IF NOT EXISTS accounts (id UUID PRIMARY KEY, balance int8)"); } } ``` The sample app uses JDBC and the [Data Access Object (DAO)](https://wikipedia.org/wiki/Data_access_object) pattern to map Java methods to SQL operations. It consists of two classes: 1. `BasicExample`, which is where the application logic lives. 2. `BasicExampleDAO`, which is used by the application to access the data store (in this case CockroachDB). This class also includes a helper function (`runSql`) that runs SQL statements inside a transaction, [retrying statements](/docs/v26.4/transactions#transaction-retries) as needed. The `main` method of the app performs the following steps which roughly correspond to method calls in the `BasicExample` class. | Step | Method | | - | - | | 1. Insert account data using a `Map` that corresponds to the input to `INSERT` on the backend | `BasicExampleDAO.updateAccounts(Map balance)` | | 2. Transfer money from one account to another, printing out account balances before and after the transfer | `BasicExampleDAO.transferFunds(UUID from, UUID to, BigDecimal amount)` | | 3. Insert random account data using JDBC's bulk insertion support | `BasicExampleDAO.bulkInsertRandomAccountData()` | | 4. Print out some account data | `BasicExampleDAO.readAccounts(int limit)` | It does all of the above using the practices we recommend for using JDBC with CockroachDB, which are listed in the [Recommended Practices](#recommended-practices) section below. ## Step 3. Update the connection configuration 1. Navigate to the `example-app-java-jdbc` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cd example-app-java-jdbc ``` 2. Set the `JDBC_DATABASE_URL` environment variable to a JDBC-compatible connection string: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export JDBC_DATABASE_URL=jdbc:postgresql://localhost:26257/defaultdb?sslmode=disable&user=root ``` 1. Paste in the command you copied earlier: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export JDBC_DATABASE_URL="{connection-string}" ``` Where `{connection-string}` is the JDBC connection string from the command you copied earlier. 2. Use the `cockroach convert-url` command to convert the connection string that you copied earlier to a [valid connection string for JDBC connections](/docs/v26.4/connect-to-the-database?filters=java): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach convert-url --url $DATABASE_URL ``` ``` ... # Connection URL for JDBC (Java and JVM-based languages): jdbc:postgresql://{host}:{port}/{database}?password={password}&sslmode=verify-full&user={username} ``` 3. Set the `JDBC_DATABASE_URL` environment variable to the JDBC-compatible connection string: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export JDBC_DATABASE_URL="{jdbc-connection-string}" ``` ## Step 4. Run the code Compile and run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ./gradlew run ``` The output will look like the following: ``` com.cockroachlabs.BasicExampleDAO.createAccountsTable: 'CREATE TABLE IF NOT EXISTS accounts (id UUID PRIMARY KEY, balance int8)' com.cockroachlabs.BasicExampleDAO.updateAccounts: 'INSERT INTO accounts (id, balance) VALUES ('b5679853-b968-4206-91ec-68945fa3e716', 250)' com.cockroachlabs.BasicExampleDAO.updateAccounts: 'INSERT INTO accounts (id, balance) VALUES ('d1c41041-6589-4b06-8d7c-b9d6d901727e', 1000)' BasicExampleDAO.updateAccounts: => 2 total updated accounts main: => Account balances at time '15:09:08.902': ID 1 => $1000 ID 2 => $250 com.cockroachlabs.BasicExampleDAO.transferFunds: 'UPSERT INTO accounts (id, balance) VALUES('d99e6bb5-ecd1-48e5-b6b6-47fc9a4bc752', ((SELECT balance FROM accounts WHERE id = 'd99e6bb5-ecd1-48e5-b6b6-47fc9a4bc752') - 100)),('6f0c1f94-509a-47e3-a9ab-6a9e3965945c', ((SELECT balance FROM accounts WHERE id = '6f0c1f94-509a-47e3-a9ab-6a9e3965945c') + 100))' BasicExampleDAO.transferFunds: => $100 transferred between accounts d99e6bb5-ecd1-48e5-b6b6-47fc9a4bc752 and 6f0c1f94-509a-47e3-a9ab-6a9e3965945c, 2 rows updated main: => Account balances at time '15:09:09.142': ID 1 => $1000 ID 2 => $250 BasicExampleDAO.bulkInsertRandomAccountData: 'INSERT INTO accounts (id, balance) VALUES ('b70a0c48-fdf4-42ea-b07a-2fea83d77c7d', '287108674'::numeric)' => 128 row(s) updated in this batch BasicExampleDAO.bulkInsertRandomAccountData: 'INSERT INTO accounts (id, balance) VALUES ('75a5f894-532a-464d-b37e-a4b9ec1c1db6', '189904311'::numeric)' => 128 row(s) updated in this batch BasicExampleDAO.bulkInsertRandomAccountData: 'INSERT INTO accounts (id, balance) VALUES ('0803968f-ba07-4ece-82d5-24d4da9fdee9', '832474731'::numeric)' => 128 row(s) updated in this batch BasicExampleDAO.bulkInsertRandomAccountData: 'INSERT INTO accounts (id, balance) VALUES ('082e634d-4930-41eb-9839-298632a5530a', '665918272'::numeric)' => 128 row(s) updated in this batch BasicExampleDAO.bulkInsertRandomAccountData: => finished, 512 total rows inserted com.cockroachlabs.BasicExampleDAO.readAccounts: 'SELECT id, balance FROM accounts LIMIT 10' balance => 424934060 balance => 62220740 balance => 454671673 balance => 556061618 balance => 450164589 balance => 996867752 balance => 55869978 balance => 747446662 balance => 175832969 balance => 181799597 BUILD SUCCESSFUL in 8s 3 actionable tasks: 3 executed ``` ## Recommended practices ### Set session variables [Session variables](/docs/v26.4/session-variables) can be set in the JDBC connection string or as properties of the JDBC data source. To set the session variable in the JDBC connection string, add them to the [`options` parameter](/docs/v26.4/connection-parameters#supported-options-parameters): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export JDBC_DATABASE_URL=jdbc:postgresql://{host}:{port}/{database}?options=-c%20{session variable name}%3D{session variable value} ``` Where: * `{session variable name}` is the name of the session variable. * `{session variable value}` is the value of the session variable. URL encode the `options` parameter to make sure the JDBC connection URL is parsed correctly. For example, the following URL encoded `options` parameter: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export JDBC_DATABASE_URL=jdbc:postgres://localhost:26257/movr?options=-c%20sql_safe_updates%3Dtrue ``` is equivalent to: ``` options=-c unbounded_parallel_scans=on ``` To set session variables as properties of the JDBC data source, set `options` using `setProperty`: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Properties props = new Properties(); props.setProperty("options", "-c {session variable name}={session variable value}"); Connection conn = DriverManager.getConnection(url, props); ``` Where: * `{session variable name}` is the name of the session variable. * `{session variable value}` is the value of the session variable. To add more than one session variable, append additional `-c` settings: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} props.setProperty("options", "-c sql_safe_updates=true -c statement_timeout=30"); ``` ### Generate PKCS8 keys for user authentication You can pass the [`--also-generate-pkcs8-key` flag](/docs/v26.4/cockroach-cert#flag-pkcs8) to [`cockroach cert`](/docs/v26.4/cockroach-cert#flag-pkcs8) to generate a key in [PKCS#8 format](https://tools.ietf.org/html/rfc5208), which is the standard key encoding format in Java. For example, if you have the user `max`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-client max --certs-dir=certs --ca-key=my-safe-directory/ca.key --also-generate-pkcs8-key ``` The generated PKCS8 key will be named `client.max.key.pk8`. > [!NOTE] > > CockroachDB Cloud does not yet support certificate-based user authentication. ### Use `IMPORT INTO` to read in large data sets If you are trying to get a large data set into CockroachDB all at once (a bulk import), avoid writing client-side code altogether and use the [`IMPORT INTO`](/docs/v26.4/import-into) statement instead. It is much faster and more efficient than making a series of [`INSERT`s](/docs/v26.4/insert) and [`UPDATE`s](/docs/v26.4/update). It bypasses the [SQL layer](/docs/v26.4/architecture/sql-layer) altogether and writes directly to the [storage layer](/docs/v26.4/architecture/storage-layer) of the database. For more information about importing data from PostgreSQL, see [Migrate from PostgreSQL](/docs/molt/migrate-to-cockroachdb). For more information about importing data from MySQL, see [Migrate from MySQL](/docs/molt/migrate-to-cockroachdb?filters=mysql). ### Use `reWriteBatchedInserts` for increased speed We strongly recommend setting `reWriteBatchedInserts=true`; we have seen 2-3x performance improvements with it enabled. From [the JDBC connection parameters documentation](https://jdbc.postgresql.org/documentation/use/#connection-parameters): > This will change batch inserts from `insert into foo (col1, col2, col3) values (1,2,3)` into `insert into foo (col1, col2, col3) values (1,2,3), (4,5,6)` this provides 2-3x performance improvement ### Use a batch size of 128 PGJDBC's batching support only works with [powers of two](https://github.com/pgjdbc/pgjdbc/blob/7b52b0c9e5b9aa9a9c655bb68f23bf4ec57fd51c/pgjdbc/src/main/java/org/postgresql/jdbc/PgPreparedStatement.java#L1597), and will split batches of other sizes up into multiple sub-batches. This means that a batch of size 128 can be 6x faster than a batch of size 250. The code snippet below shows a pattern for using a batch size of 128, and is taken from the longer example above (specifically, the `BasicExampleDAO.bulkInsertRandomAccountData()` method). Specifically, it does the following: 1. Turn off auto-commit so you can manage the transaction lifecycle and thus the size of the batch inserts. 2. Given an overall update size of 500 rows (for example), split it into batches of size 128 and execute each batch in turn. 3. Finally, commit the batches of statements you've just executed. ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} int BATCH_SIZE = 128; connection.setAutoCommit(false); try (PreparedStatement pstmt = connection.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, ?)")) { for (int i=0; i<=(500/BATCH_SIZE);i++) { for (int j=0; j %s row(s) updated in this batch\n", count.length); // Verifying 128 rows in the batch } connection.commit(); } ``` ### Retrieve large data sets in chunks using cursors CockroachDB now supports the PostgreSQL wire-protocol cursors for implicit transactions and explicit transactions executed to completion. This means the [PGJDBC driver](https://jdbc.postgresql.org) can use this protocol to stream queries with large result sets. This is much faster than [paginating through results in SQL using `LIMIT .. OFFSET`](/docs/v26.4/pagination). For instructions showing how to use cursors in your Java code, see [Getting results based on a cursor](https://jdbc.postgresql.org/documentation/query/#getting-results-based-on-a-cursor) from the PGJDBC documentation. Note that interleaved execution (partial execution of multiple statements within the same connection and transaction) is not supported when [`Statement.setFetchSize()`](https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#setFetchSize-int-) is used. ### Connection pooling For guidance on connection pooling, with an example using JDBC and [HikariCP](https://github.com/brettwooldridge/HikariCP), see [Connection Pooling](/docs/v26.4/connection-pooling). ## What's next? Read more about using the [Java JDBC driver](https://jdbc.postgresql.org/). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Java App with CockroachDB and Hibernate Source: https://docs.cockroachlabs.com/docs/stable/build-a-java-app-with-cockroachdb-hibernate This tutorial shows you how build a simple Java application with CockroachDB and the Hibernate ORM. > [!NOTE] > > We recommend using Java versions 8+ with CockroachDB. For another use of Hibernate with CockroachDB, see our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_java_hibernate). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection information > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **Parameters only** from the **Select option** dropdown. > > 2. Copy the connection information for each parameter displayed and save it in a secure location. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the sample code Clone the `example-app-java-hibernate` repo to your machine: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} git clone https://github.com/cockroachlabs/example-app-java-hibernate/ ``` > [!NOTE] > > The version of the CockroachDB Hibernate dialect in `hibernate.cfg.xml` corresponds to a version of CockroachDB. For more information, see [Install Client Drivers: Hibernate](/docs/v26.4/install-client-drivers). ## Step 3. Run the code The sample code in this tutorial ([`Sample.java`](#code-contents)) uses Hibernate to map Java methods to SQL operations. The code performs the following operations, which roughly correspond to method calls in the `Sample` class: 1. Creates an `accounts` table as specified by the `Account` mapping class. 2. Inserts rows into the table with the `addAccounts()` method. 3. Transfers money from one account to another with the `transferFunds()` method. 4. Prints out account balances before and after the transfer with the `getAccountBalance()` method. In addition, the code shows a pattern for automatically handling [transaction retries](/docs/v26.4/transaction-retry-error-example) by wrapping transactions in a higher-order function named `runTransaction()`. It also includes a method for testing the retry handling logic (`Sample.forceRetryLogic()`), which will be run if you set the `FORCE_RETRY` variable to `true`. It does all of the above using the practices we recommend for using Hibernate (and the underlying JDBC connection) with CockroachDB, which are listed in the [Recommended Practices](#recommended-practices) section below. The contents of `Sample.java`: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.cockroachlabs; public class Sample implements Serializable { private static final Random RAND = new Random(); private static final boolean FORCE_RETRY = false; private static final String RETRY_SQL_STATE = "40001"; private static final int MAX_ATTEMPT_COUNT = 6; private static Function addAccounts() throws JDBCException { Function f = s -> { BigDecimal rv = new BigDecimal(0); try { s.save(new Account(1, 1000)); s.save(new Account(2, 250)); s.save(new Account(3, 314159)); rv = BigDecimal.valueOf(1); System.out.printf("APP: addAccounts() --> %.2f\n", rv); } catch (JDBCException e) { throw e; } return rv; }; return f; } private static Function transferFunds(long fromId, long toId, BigDecimal amount) throws JDBCException { Function f = s -> { BigDecimal rv = new BigDecimal(0); try { Account fromAccount = (Account) s.get(Account.class, fromId); Account toAccount = (Account) s.get(Account.class, toId); if (!(amount.compareTo(fromAccount.getBalance()) > 0)) { fromAccount.balance = fromAccount.balance.subtract(amount); toAccount.balance = toAccount.balance.add(amount); s.save(fromAccount); s.save(toAccount); rv = amount; System.out.printf("APP: transferFunds(%d, %d, %.2f) --> %.2f\n", fromId, toId, amount, rv); } } catch (JDBCException e) { throw e; } return rv; }; return f; } // Test our retry handling logic if FORCE_RETRY is true. This // method is only used to test the retry logic. It is not // intended for production code. private static Function forceRetryLogic() throws JDBCException { Function f = s -> { BigDecimal rv = new BigDecimal(-1); try { System.out.printf("APP: testRetryLogic: BEFORE EXCEPTION\n"); s.createNativeQuery("SELECT crdb_internal.force_retry('1s')").executeUpdate(); } catch (JDBCException e) { System.out.printf("APP: testRetryLogic: AFTER EXCEPTION\n"); throw e; } return rv; }; return f; } private static Function getAccountBalance(long id) throws JDBCException { Function f = s -> { BigDecimal balance; try { Account account = s.get(Account.class, id); balance = account.getBalance(); System.out.printf("APP: getAccountBalance(%d) --> %.2f\n", id, balance); } catch (JDBCException e) { throw e; } return balance; }; return f; } // Run SQL code in a way that automatically handles the // transaction retry logic so we don't have to duplicate it in // various places. private static BigDecimal runTransaction(Session session, Function fn) { BigDecimal rv = new BigDecimal(0); int attemptCount = 0; while (attemptCount < MAX_ATTEMPT_COUNT) { attemptCount++; if (attemptCount > 1) { System.out.printf("APP: Entering retry loop again, iteration %d\n", attemptCount); } Transaction txn = session.beginTransaction(); System.out.printf("APP: BEGIN;\n"); if (attemptCount == MAX_ATTEMPT_COUNT) { String err = String.format("hit max of %s attempts, aborting", MAX_ATTEMPT_COUNT); throw new RuntimeException(err); } // This block is only used to test the retry logic. // It is not necessary in production code. See also // the method 'testRetryLogic()'. if (FORCE_RETRY) { session.createNativeQuery("SELECT now()").list(); } try { rv = fn.apply(session); if (!rv.equals(-1)) { txn.commit(); System.out.printf("APP: COMMIT;\n"); break; } } catch (JDBCException e) { if (RETRY_SQL_STATE.equals(e.getSQLState())) { // Since this is a transaction retry error, we // roll back the transaction and sleep a little // before trying again. Each time through the // loop we sleep for a little longer than the last // time (A.K.A. exponential backoff). System.out.printf("APP: retryable exception occurred:\n sql state = [%s]\n message = [%s]\n retry counter = %s\n", e.getSQLState(), e.getMessage(), attemptCount); System.out.printf("APP: ROLLBACK;\n"); txn.rollback(); int sleepMillis = (int) (Math.pow(2, attemptCount) * 100) + RAND.nextInt(100); System.out.printf("APP: Hit 40001 transaction retry error, sleeping %s milliseconds\n", sleepMillis); try { Thread.sleep(sleepMillis); } catch (InterruptedException ignored) { // no-op } rv = BigDecimal.valueOf(-1); } else { throw e; } } } return rv; } public static void main(String[] args) { // Create a SessionFactory based on our hibernate.cfg.xml configuration // file, which defines how to connect to the database. SessionFactory sessionFactory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Account.class) .buildSessionFactory(); try (Session session = sessionFactory.openSession()) { long fromAccountId = 1; long toAccountId = 2; BigDecimal transferAmount = BigDecimal.valueOf(100); if (FORCE_RETRY) { System.out.printf("APP: About to test retry logic in 'runTransaction'\n"); runTransaction(session, forceRetryLogic()); } else { runTransaction(session, addAccounts()); BigDecimal fromBalance = runTransaction(session, getAccountBalance(fromAccountId)); BigDecimal toBalance = runTransaction(session, getAccountBalance(toAccountId)); if (!fromBalance.equals(-1) && !toBalance.equals(-1)) { // Success! System.out.printf("APP: getAccountBalance(%d) --> %.2f\n", fromAccountId, fromBalance); System.out.printf("APP: getAccountBalance(%d) --> %.2f\n", toAccountId, toBalance); } // Transfer $100 from account 1 to account 2 BigDecimal transferResult = runTransaction(session, transferFunds(fromAccountId, toAccountId, transferAmount)); if (!transferResult.equals(-1)) { // Success! System.out.printf("APP: transferFunds(%d, %d, %.2f) --> %.2f \n", fromAccountId, toAccountId, transferAmount, transferResult); BigDecimal fromBalanceAfter = runTransaction(session, getAccountBalance(fromAccountId)); BigDecimal toBalanceAfter = runTransaction(session, getAccountBalance(toAccountId)); if (!fromBalanceAfter.equals(-1) && !toBalanceAfter.equals(-1)) { // Success! System.out.printf("APP: getAccountBalance(%d) --> %.2f\n", fromAccountId, fromBalanceAfter); System.out.printf("APP: getAccountBalance(%d) --> %.2f\n", toAccountId, toBalanceAfter); } } } } finally { sessionFactory.close(); } } } ``` ### Update the connection configuration Open `src/main/resources/hibernate.cfg.xml`, and set the `hibernate.connection.url`, `hibernate.connection.username`, and `hibernate.connection.password` properties, using the connection information that you obtained from the Cloud Console: ```xml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} jdbc:postgresql://{host}:{port}/defaultdb?sslmode=verify-full{username}{password} 1.00 APP: COMMIT; APP: BEGIN; APP: getAccountBalance(1) --> 1000.00 APP: COMMIT; APP: BEGIN; APP: getAccountBalance(2) --> 250.00 APP: COMMIT; APP: getAccountBalance(1) --> 1000.00 APP: getAccountBalance(2) --> 250.00 APP: BEGIN; APP: transferFunds(1, 2, 100.00) --> 100.00 APP: COMMIT; APP: transferFunds(1, 2, 100.00) --> 100.00 APP: BEGIN; APP: getAccountBalance(1) --> 900.00 APP: COMMIT; APP: BEGIN; APP: getAccountBalance(2) --> 350.00 APP: COMMIT; APP: getAccountBalance(1) --> 900.00 APP: getAccountBalance(2) --> 350.00 ``` ## Recommended practices ### Generate PKCS8 keys for client authentication You can pass the [`--also-generate-pkcs8-key` flag](/docs/v26.4/cockroach-cert#flag-pkcs8) to [`cockroach cert`](/docs/v26.4/cockroach-cert#flag-pkcs8) to generate a key in [PKCS#8 format](https://tools.ietf.org/html/rfc5208), which is the standard key encoding format in Java. For example, if you have the user `max`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-client max --certs-dir=certs --ca-key=my-safe-directory/ca.key --also-generate-pkcs8-key ``` The generated PKCS8 key will be named `client.max.key.pk8`. > [!NOTE] > > CockroachDB Cloud does not yet support certificate-based user authentication. ### Use `IMPORT INTO` to read in large data sets If you are trying to get a large data set into CockroachDB all at once (a bulk import), avoid writing client-side code altogether and use the [`IMPORT INTO`](/docs/v26.4/import-into) statement instead. It is much faster and more efficient than making a series of [`INSERT`s](/docs/v26.4/insert) and [`UPDATE`s](/docs/v26.4/update). It bypasses the [SQL layer](/docs/v26.4/architecture/sql-layer) altogether and writes directly to the [storage layer](/docs/v26.4/architecture/storage-layer) of the database. For more information about importing data from PostgreSQL, see [Migrate from PostgreSQL](/docs/molt/migrate-to-cockroachdb). For more information about importing data from MySQL, see [Migrate from MySQL](/docs/molt/migrate-to-cockroachdb?filters=mysql). ### Use `reWriteBatchedInserts` for increased speed We strongly recommend setting `reWriteBatchedInserts=true`; we have seen 2-3x performance improvements with it enabled. From [the JDBC connection parameters documentation](https://jdbc.postgresql.org/documentation/use/#connection-parameters): > This will change batch inserts from `insert into foo (col1, col2, col3) values (1,2,3)` into `insert into foo (col1, col2, col3) values (1,2,3), (4,5,6)` this provides 2-3x performance improvement ### Retrieve large data sets in chunks using cursors CockroachDB now supports the PostgreSQL wire-protocol cursors for implicit transactions and explicit transactions executed to completion. This means the [PGJDBC driver](https://jdbc.postgresql.org) can use this protocol to stream queries with large result sets. This is much faster than [paginating through results in SQL using `LIMIT .. OFFSET`](/docs/v26.4/pagination). For instructions showing how to use cursors in your Java code, see [Getting results based on a cursor](https://jdbc.postgresql.org/documentation/query/#getting-results-based-on-a-cursor) from the PGJDBC documentation. Note that interleaved execution (partial execution of multiple statements within the same connection and transaction) is not supported when [`Statement.setFetchSize()`](https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#setFetchSize-int-) is used. ## What's next? Read more about using the [Hibernate ORM](http://hibernate.org/orm/), or check out a more realistic implementation of Hibernate with CockroachDB in our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Java App with CockroachDB and jOOQ Source: https://docs.cockroachlabs.com/docs/stable/build-a-java-app-with-cockroachdb-jooq This tutorial shows you how build a simple Java application with CockroachDB and [jOOQ](https://www.jooq.org/). CockroachDB is supported in jOOQ [Professional and Enterprise editions](https://www.jooq.org/download/#databases). > [!NOTE] > > We recommend using Java versions 8+ with CockroachDB. > [!TIP] > > For another use of jOOQ with CockroachDB, see our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. ## Before you begin 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac). 2. Start up a [secure](/docs/v26.4/secure-a-cluster) or [insecure](/docs/v26.4/start-a-local-cluster) local cluster. 3. Choose the instructions that correspond to whether your cluster is secure or insecure: > [!CAUTION] > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 1. Install Maven This tutorial uses the [Maven build tool](https://gradle.org/) to manage application dependencies. To install Maven on Mac, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ brew install maven ``` To install Maven on a Debian-based Linux distribution like Ubuntu: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ apt-get install maven ``` For other ways to install Maven, see [its official documentation](https://maven.apache.org/install.html). ## Step 2. Install jOOQ Download the free trial of jOOQ Professional or Enterprise edition from [jOOQ's website](https://www.jooq.org/download), and unzip the file. To install jOOQ to your machine's local Maven repository, run the `maven-install.sh` script included in the jOOQ install folder: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ chmod +x maven-install.sh ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ./maven-install.sh ``` > [tab] Secure > > ## Step 3. Create the `maxroach` user and `bank` database > > Start the [built-in SQL shell](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --certs-dir=certs > ``` > > In the SQL shell, issue the following statements to create the `maxroach` user and `bank` database: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER IF NOT EXISTS maxroach; > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > Give the `maxroach` user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO maxroach; > ``` > > Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > > ## Step 4. Generate a certificate for the `maxroach` user > > Create a certificate and key for the `maxroach` user by running the following command. The code samples will run as this user. > > The [`--also-generate-pkcs8-key` flag](/docs/v26.4/cockroach-cert#flag-pkcs8) generates a key in [PKCS#8 format](https://tools.ietf.org/html/rfc5208), which is the standard key encoding format in Java. In this case, the generated PKCS8 key will be named `client.maxroach.key.pk8`. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach cert create-client maxroach --certs-dir=certs --ca-key=my-safe-directory/ca.key --also-generate-pkcs8-key > ``` > > ## Step 5. Run the Java code > > The code below uses jOOQ to map Java methods to SQL operations. It performs the following steps, some of which correspond to method calls of the `Sample` class. > > 1. Inputs the `db.sql` file to the database. `db.sql` includes SQL statements that create an `accounts` table in the `bank` database. > 2. Inserts rows into the `accounts` table using `session.save(new Account(int id, int balance))` (see `Sample.addAccounts()`). > 3. Transfers money from one account to another, printing out account balances before and after the transfer (see `transferFunds(long fromId, long toId, long amount)`). > 4. Prints out account balances before and after the transfer (see `Sample.getAccountBalance(long id)`). > > In addition, the code shows a pattern for automatically handling [transaction retries](/docs/v26.4/transaction-retry-error-example) by wrapping transactions in a higher-order function `Sample.runTransaction()`. It also includes a method for testing the retry handling logic (`Sample.forceRetryLogic()`), which will be run if you set the `FORCE_RETRY` variable to `true`. > > To run it: > > 1. Download and unzip [jooq-basic-sample.zip](https://docs.cockroachlabs.com/files/jooq-basic-sample/jooq-basic-sample.zip). > 2. Open `jooq-basic-sample/src/main/java/com/cockroachlabs/Sample.java`, and edit the connection string passed to `DriverManager.getConnection()` in the `Sample` class's `main()` method so that the certificate paths are fully and correctly specified. > 3. Compile and run the code using Maven: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cd jooq-basic-sample > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mvn compile > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mvn exec:java -Dexec.mainClass=com.cockroachlabs.Sample > ``` > > Here are the contents of `Sample.java`, the Java file containing the main `Sample` class: > > ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > package com.cockroachlabs; > > public class Sample { > > private static final Random RAND = new Random(); > private static final boolean FORCE_RETRY = false; > private static final String RETRY_SQL_STATE = "40001"; > private static final int MAX_ATTEMPT_COUNT = 6; > > private static Function addAccounts() { > return ctx -> { > long rv = 0; > > ctx.delete(ACCOUNTS).execute(); > ctx.batchInsert( > new AccountsRecord(1L, 1000L), > new AccountsRecord(2L, 250L), > new AccountsRecord(3L, 314159L) > ).execute(); > > rv = 1; > System.out.printf("APP: addAccounts() --> %d\n", rv); > return rv; > }; > } > > private static Function transferFunds(long fromId, long toId, long amount) { > return ctx -> { > long rv = 0; > > AccountsRecord fromAccount = ctx.fetchSingle(ACCOUNTS, ACCOUNTS.ID.eq(fromId)); > AccountsRecord toAccount = ctx.fetchSingle(ACCOUNTS, ACCOUNTS.ID.eq(toId)); > > if (!(amount > fromAccount.getBalance())) { > fromAccount.setBalance(fromAccount.getBalance() - amount); > toAccount.setBalance(toAccount.getBalance() + amount); > > ctx.batchUpdate(fromAccount, toAccount).execute(); > rv = amount; > System.out.printf("APP: transferFunds(%d, %d, %d) --> %d\n", fromId, toId, amount, rv); > } > > return rv; > }; > } > > // Test our retry handling logic if FORCE_RETRY is true. This > // method is only used to test the retry logic. It is not > // intended for production code. > private static Function forceRetryLogic() { > return ctx -> { > long rv = -1; > try { > System.out.printf("APP: testRetryLogic: BEFORE EXCEPTION\n"); > ctx.execute("SELECT crdb_internal.force_retry('1s')"); > } catch (DataAccessException e) { > System.out.printf("APP: testRetryLogic: AFTER EXCEPTION\n"); > throw e; > } > return rv; > }; > } > > private static Function getAccountBalance(long id) { > return ctx -> { > AccountsRecord account = ctx.fetchSingle(ACCOUNTS, ACCOUNTS.ID.eq(id)); > long balance = account.getBalance(); > System.out.printf("APP: getAccountBalance(%d) --> %d\n", id, balance); > return balance; > }; > } > > // Run SQL code in a way that automatically handles the > // transaction retry logic so we do not have to duplicate it in > // various places. > private static long runTransaction(DSLContext session, Function fn) { > AtomicLong rv = new AtomicLong(0L); > AtomicInteger attemptCount = new AtomicInteger(0); > > while (attemptCount.get() < MAX_ATTEMPT_COUNT) { > attemptCount.incrementAndGet(); > > if (attemptCount.get() > 1) { > System.out.printf("APP: Entering retry loop again, iteration %d\n", attemptCount.get()); > } > > if (session.connectionResult(connection -> { > connection.setAutoCommit(false); > System.out.printf("APP: BEGIN;\n"); > > if (attemptCount.get() == MAX_ATTEMPT_COUNT) { > String err = String.format("hit max of %s attempts, aborting", MAX_ATTEMPT_COUNT); > throw new RuntimeException(err); > } > > // This block is only used to test the retry logic. > // It is not necessary in production code. See also > // the method 'testRetryLogic()'. > if (FORCE_RETRY) { > session.fetch("SELECT now()"); > } > > try { > rv.set(fn.apply(session)); > if (rv.get() != -1) { > connection.commit(); > System.out.printf("APP: COMMIT;\n"); > return true; > } > } catch (DataAccessException | SQLException e) { > String sqlState = e instanceof SQLException ? ((SQLException) e).getSQLState() : ((DataAccessException) e).sqlState(); > > if (RETRY_SQL_STATE.equals(sqlState)) { > // Since this is a transaction retry error, we > // roll back the transaction and sleep a little > // before trying again. Each time through the > // loop we sleep for a little longer than the last > // time (A.K.A. exponential backoff). > System.out.printf("APP: retryable exception occurred:\n sql state = [%s]\n message = [%s]\n retry counter = %s\n", sqlState, e.getMessage(), attemptCount.get()); > System.out.printf("APP: ROLLBACK;\n"); > connection.rollback(); > int sleepMillis = (int)(Math.pow(2, attemptCount.get()) * 100) + RAND.nextInt(100); > System.out.printf("APP: Hit 40001 transaction retry error, sleeping %s milliseconds\n", sleepMillis); > try { > Thread.sleep(sleepMillis); > } catch (InterruptedException ignored) { > // no-op > } > rv.set(-1L); > } else { > throw e; > } > } > > return false; > })) { > break; > } > } > > return rv.get(); > } > > public static void main(String[] args) throws Exception { > try (Connection connection = DriverManager.getConnection( > "jdbc:postgresql://localhost:26257/bank?ssl=true&sslmode=require&sslrootcert=certs/ca.crt&sslkey=certs/client.maxroach.key.pk8&sslcert=certs/client.maxroach.crt", > "maxroach", > "" > )) { > DSLContext ctx = DSL.using(connection, SQLDialect.COCKROACHDB, new Settings() > .withExecuteLogging(true) > .withRenderQuotedNames(RenderQuotedNames.NEVER)); > > // Initialise database with db.sql script > try (InputStream in = Sample.class.getResourceAsStream("/db.sql")) { > ctx.parser().parse(Source.of(in).readString()).executeBatch(); > } > > long fromAccountId = 1; > long toAccountId = 2; > long transferAmount = 100; > > if (FORCE_RETRY) { > System.out.printf("APP: About to test retry logic in 'runTransaction'\n"); > runTransaction(ctx, forceRetryLogic()); > } else { > > runTransaction(ctx, addAccounts()); > long fromBalance = runTransaction(ctx, getAccountBalance(fromAccountId)); > long toBalance = runTransaction(ctx, getAccountBalance(toAccountId)); > if (fromBalance != -1 && toBalance != -1) { > // Success! > System.out.printf("APP: getAccountBalance(%d) --> %d\n", fromAccountId, fromBalance); > System.out.printf("APP: getAccountBalance(%d) --> %d\n", toAccountId, toBalance); > } > > // Transfer $100 from account 1 to account 2 > long transferResult = runTransaction(ctx, transferFunds(fromAccountId, toAccountId, transferAmount)); > if (transferResult != -1) { > // Success! > System.out.printf("APP: transferFunds(%d, %d, %d) --> %d \n", fromAccountId, toAccountId, transferAmount, transferResult); > > long fromBalanceAfter = runTransaction(ctx, getAccountBalance(fromAccountId)); > long toBalanceAfter = runTransaction(ctx, getAccountBalance(toAccountId)); > if (fromBalanceAfter != -1 && toBalanceAfter != -1) { > // Success! > System.out.printf("APP: getAccountBalance(%d) --> %d\n", fromAccountId, fromBalanceAfter); > System.out.printf("APP: getAccountBalance(%d) --> %d\n", toAccountId, toBalanceAfter); > } > } > } > } > } > } > ``` > > Toward the end of the output, you should see: > > ``` > APP: BEGIN; > APP: addAccounts() --> 1 > APP: COMMIT; > APP: BEGIN; > APP: getAccountBalance(1) --> 1000 > APP: COMMIT; > APP: BEGIN; > APP: getAccountBalance(2) --> 250 > APP: COMMIT; > APP: getAccountBalance(1) --> 1000 > APP: getAccountBalance(2) --> 250 > APP: BEGIN; > APP: transferFunds(1, 2, 100) --> 100 > APP: COMMIT; > APP: transferFunds(1, 2, 100) --> 100 > APP: BEGIN; > APP: getAccountBalance(1) --> 900 > APP: COMMIT; > APP: BEGIN; > APP: getAccountBalance(2) --> 350 > APP: COMMIT; > APP: getAccountBalance(1) --> 900 > APP: getAccountBalance(2) --> 350 > ``` > > To verify that the account balances were updated successfully, start the [built-in SQL client](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --certs-dir=certs > ``` > > To check the account balances, issue the following statement: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT id, balance FROM accounts; > ``` > > ``` > id | balance > +----+---------+ > 1 | 900 > 2 | 350 > 3 | 314159 > (3 rows) > ``` > [tab] Insecure > > ## Step 3. Create the `maxroach` user and `bank` database > > Start the [built-in SQL shell](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --insecure > ``` > > In the SQL shell, issue the following statements to create the `maxroach` user and `bank` database: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER IF NOT EXISTS maxroach; > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > Give the `maxroach` user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO maxroach; > ``` > > Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > > ## Step 4. Run the Java code > > The code below uses jOOQ to map Java methods to SQL operations. It performs the following steps, some of which correspond to method calls of the `Sample` class. > > 1. Inputs the `db.sql` file to the database. `db.sql` includes SQL statements that create an `accounts` table in the `bank` database. > 2. Inserts rows into the `accounts` table using `session.save(new Account(int id, int balance))` (see `Sample.addAccounts()`). > 3. Transfers money from one account to another, printing out account balances before and after the transfer (see `transferFunds(long fromId, long toId, long amount)`). > 4. Prints out account balances before and after the transfer (see `Sample.getAccountBalance(long id)`). > > In addition, the code shows a pattern for automatically handling [transaction retries](/docs/v26.4/transaction-retry-error-example) by wrapping transactions in a higher-order function `Sample.runTransaction()`. It also includes a method for testing the retry handling logic (`Sample.forceRetryLogic()`), which will be run if you set the `FORCE_RETRY` variable to `true`. > > To run it: > > 1. Download and unzip [jooq-basic-sample.zip](https://docs.cockroachlabs.com/files/jooq-basic-sample/insecure/jooq-basic-sample.zip). > 2. Compile and run the code using Maven: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cd jooq-basic-sample > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mvn compile > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mvn exec:java -Dexec.mainClass=com.cockroachlabs.Sample > ``` > > Here are the contents of `Sample.java`, the Java file containing the main `Sample` class: > > ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > package com.cockroachlabs; > > public class Sample { > > private static final Random RAND = new Random(); > private static final boolean FORCE_RETRY = false; > private static final String RETRY_SQL_STATE = "40001"; > private static final int MAX_ATTEMPT_COUNT = 6; > > private static Function addAccounts() { > return ctx -> { > long rv = 0; > > ctx.delete(ACCOUNTS).execute(); > ctx.batchInsert( > new AccountsRecord(1L, 1000L), > new AccountsRecord(2L, 250L), > new AccountsRecord(3L, 314159L) > ).execute(); > > rv = 1; > System.out.printf("APP: addAccounts() --> %d\n", rv); > return rv; > }; > } > > private static Function transferFunds(long fromId, long toId, long amount) { > return ctx -> { > long rv = 0; > > AccountsRecord fromAccount = ctx.fetchSingle(ACCOUNTS, ACCOUNTS.ID.eq(fromId)); > AccountsRecord toAccount = ctx.fetchSingle(ACCOUNTS, ACCOUNTS.ID.eq(toId)); > > if (!(amount > fromAccount.getBalance())) { > fromAccount.setBalance(fromAccount.getBalance() - amount); > toAccount.setBalance(toAccount.getBalance() + amount); > > ctx.batchUpdate(fromAccount, toAccount).execute(); > rv = amount; > System.out.printf("APP: transferFunds(%d, %d, %d) --> %d\n", fromId, toId, amount, rv); > } > > return rv; > }; > } > > // Test our retry handling logic if FORCE_RETRY is true. This > // method is only used to test the retry logic. It is not > // intended for production code. > private static Function forceRetryLogic() { > return ctx -> { > long rv = -1; > try { > System.out.printf("APP: testRetryLogic: BEFORE EXCEPTION\n"); > ctx.execute("SELECT crdb_internal.force_retry('1s')"); > } catch (DataAccessException e) { > System.out.printf("APP: testRetryLogic: AFTER EXCEPTION\n"); > throw e; > } > return rv; > }; > } > > private static Function getAccountBalance(long id) { > return ctx -> { > AccountsRecord account = ctx.fetchSingle(ACCOUNTS, ACCOUNTS.ID.eq(id)); > long balance = account.getBalance(); > System.out.printf("APP: getAccountBalance(%d) --> %d\n", id, balance); > return balance; > }; > } > > // Run SQL code in a way that automatically handles the > // transaction retry logic so we do not have to duplicate it in > // various places. > private static long runTransaction(DSLContext session, Function fn) { > AtomicLong rv = new AtomicLong(0L); > AtomicInteger attemptCount = new AtomicInteger(0); > > while (attemptCount.get() < MAX_ATTEMPT_COUNT) { > attemptCount.incrementAndGet(); > > if (attemptCount.get() > 1) { > System.out.printf("APP: Entering retry loop again, iteration %d\n", attemptCount.get()); > } > > if (session.connectionResult(connection -> { > connection.setAutoCommit(false); > System.out.printf("APP: BEGIN;\n"); > > if (attemptCount.get() == MAX_ATTEMPT_COUNT) { > String err = String.format("hit max of %s attempts, aborting", MAX_ATTEMPT_COUNT); > throw new RuntimeException(err); > } > > // This block is only used to test the retry logic. > // It is not necessary in production code. See also > // the method 'testRetryLogic()'. > if (FORCE_RETRY) { > session.fetch("SELECT now()"); > } > > try { > rv.set(fn.apply(session)); > if (rv.get() != -1) { > connection.commit(); > System.out.printf("APP: COMMIT;\n"); > return true; > } > } catch (DataAccessException | SQLException e) { > String sqlState = e instanceof SQLException ? ((SQLException) e).getSQLState() : ((DataAccessException) e).sqlState(); > > if (RETRY_SQL_STATE.equals(sqlState)) { > // Since this is a transaction retry error, we > // roll back the transaction and sleep a little > // before trying again. Each time through the > // loop we sleep for a little longer than the last > // time (A.K.A. exponential backoff). > System.out.printf("APP: retryable exception occurred:\n sql state = [%s]\n message = [%s]\n retry counter = %s\n", sqlState, e.getMessage(), attemptCount.get()); > System.out.printf("APP: ROLLBACK;\n"); > connection.rollback(); > int sleepMillis = (int)(Math.pow(2, attemptCount.get()) * 100) + RAND.nextInt(100); > System.out.printf("APP: Hit 40001 transaction retry error, sleeping %s milliseconds\n", sleepMillis); > try { > Thread.sleep(sleepMillis); > } catch (InterruptedException ignored) { > // no-op > } > rv.set(-1L); > } else { > throw e; > } > } > > return false; > })) { > break; > } > } > > return rv.get(); > } > > public static void main(String[] args) throws Exception { > try (Connection connection = DriverManager.getConnection( > "jdbc:postgresql://localhost:26257/bank?sslmode=disable", > "maxroach", > "" > )) { > DSLContext ctx = DSL.using(connection, SQLDialect.COCKROACHDB, new Settings() > .withExecuteLogging(true) > .withRenderQuotedNames(RenderQuotedNames.NEVER)); > > // Initialise database with db.sql script > try (InputStream in = Sample.class.getResourceAsStream("/db.sql")) { > ctx.parser().parse(Source.of(in).readString()).executeBatch(); > } > > long fromAccountId = 1; > long toAccountId = 2; > long transferAmount = 100; > > if (FORCE_RETRY) { > System.out.printf("APP: About to test retry logic in 'runTransaction'\n"); > runTransaction(ctx, forceRetryLogic()); > } else { > > runTransaction(ctx, addAccounts()); > long fromBalance = runTransaction(ctx, getAccountBalance(fromAccountId)); > long toBalance = runTransaction(ctx, getAccountBalance(toAccountId)); > if (fromBalance != -1 && toBalance != -1) { > // Success! > System.out.printf("APP: getAccountBalance(%d) --> %d\n", fromAccountId, fromBalance); > System.out.printf("APP: getAccountBalance(%d) --> %d\n", toAccountId, toBalance); > } > > // Transfer $100 from account 1 to account 2 > long transferResult = runTransaction(ctx, transferFunds(fromAccountId, toAccountId, transferAmount)); > if (transferResult != -1) { > // Success! > System.out.printf("APP: transferFunds(%d, %d, %d) --> %d \n", fromAccountId, toAccountId, transferAmount, transferResult); > > long fromBalanceAfter = runTransaction(ctx, getAccountBalance(fromAccountId)); > long toBalanceAfter = runTransaction(ctx, getAccountBalance(toAccountId)); > if (fromBalanceAfter != -1 && toBalanceAfter != -1) { > // Success! > System.out.printf("APP: getAccountBalance(%d) --> %d\n", fromAccountId, fromBalanceAfter); > System.out.printf("APP: getAccountBalance(%d) --> %d\n", toAccountId, toBalanceAfter); > } > } > } > } > } > } > ``` > > Toward the end of the output, you should see: > > ``` > APP: BEGIN; > APP: addAccounts() --> 1 > APP: COMMIT; > APP: BEGIN; > APP: getAccountBalance(1) --> 1000 > APP: COMMIT; > APP: BEGIN; > APP: getAccountBalance(2) --> 250 > APP: COMMIT; > APP: getAccountBalance(1) --> 1000 > APP: getAccountBalance(2) --> 250 > APP: BEGIN; > APP: transferFunds(1, 2, 100) --> 100 > APP: COMMIT; > APP: transferFunds(1, 2, 100) --> 100 > APP: BEGIN; > APP: getAccountBalance(1) --> 900 > APP: COMMIT; > APP: BEGIN; > APP: getAccountBalance(2) --> 350 > APP: COMMIT; > APP: getAccountBalance(1) --> 900 > APP: getAccountBalance(2) --> 350 > ``` > > To verify that the account balances were updated successfully, start the [built-in SQL client](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --insecure > ``` > > To check the account balances, issue the following statement: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT id, balance FROM accounts; > ``` > > ``` > id | balance > +----+---------+ > 1 | 900 > 2 | 350 > 3 | 314159 > (3 rows) > ``` ## What's next? Read more about using [jOOQ](https://www.jooq.org/), or check out a more realistic implementation of jOOQ with CockroachDB in our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. You might also be interested in the following pages: * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Connection Pooling](/docs/v26.4/connection-pooling) * [Data Replication](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) # Build a Simple CRUD Node.js App with CockroachDB and the node-postgres Driver Source: https://docs.cockroachlabs.com/docs/stable/build-a-nodejs-app-with-cockroachdb This tutorial shows you how build a simple Node.js application with CockroachDB and the [node-postgres driver](https://node-postgres.com/). > [!NOTE] > > This tutorial assumes you are running under [`SERIALIZABLE`](/docs/v26.4/demo-serializable) isolation, which requires client-side retry handling for [serialization errors](/docs/v26.4/transaction-retry-error-reference). ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_node_postgres). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-node-postgres ``` The project has the following directory structure: ``` ├── README.md ├── app.js ├── dbinit.sql └── package.json ``` The `dbinit.sql` file initializes the database schema that the application uses: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE TABLE accounts ( id UUID PRIMARY KEY, balance INT8 ); ``` The `app.js` file contains the code for `INSERT`, `SELECT`, `UPDATE`, and `DELETE` SQL operations: ```js theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} const { Pool } = require("pg"); const { v4: uuidv4 } = require("uuid"); var accountValues = Array(3); // Wrapper for a transaction. This automatically re-calls the operation with // the client as an argument as long as the database server asks for // the transaction to be retried. async function retryTxn(n, max, client, operation, callback) { const backoffInterval = 100; // millis const maxTries = 5; let tries = 0; while (true) { await client.query('BEGIN;'); tries++; try { const result = await operation(client, callback); await client.query('COMMIT;'); return result; } catch (err) { await client.query('ROLLBACK;'); if (err.code !== '40001' || tries == maxTries) { throw err; } else { console.log('Transaction failed. Retrying.'); console.log(err.message); await new Promise(r => setTimeout(r, tries * backoffInterval)); } } } } // This function is called within the first transaction. It inserts some initial values into the "accounts" table. async function initTable(client, callback) { let i = 0; while (i < accountValues.length) { accountValues[i] = await uuidv4(); i++; } const insertStatement = "INSERT INTO accounts (id, balance) VALUES ($1, 1000), ($2, 250), ($3, 0);"; await client.query(insertStatement, accountValues, callback); const selectBalanceStatement = "SELECT id, balance FROM accounts;"; await client.query(selectBalanceStatement, callback); } // This function updates the values of two rows, simulating a "transfer" of funds. async function transferFunds(client, callback) { const from = accountValues[0]; const to = accountValues[1]; const amount = 100; const selectFromBalanceStatement = "SELECT balance FROM accounts WHERE id = $1;"; const selectFromValues = [from]; await client.query( selectFromBalanceStatement, selectFromValues, (err, res) => { if (err) { return callback(err); } else if (res.rows.length === 0) { console.log("account not found in table"); return callback(err); } var acctBal = res.rows[0].balance; if (acctBal < amount) { return callback(new Error("insufficient funds")); } } ); const updateFromBalanceStatement = "UPDATE accounts SET balance = balance - $1 WHERE id = $2;"; const updateFromValues = [amount, from]; await client.query(updateFromBalanceStatement, updateFromValues, callback); const updateToBalanceStatement = "UPDATE accounts SET balance = balance + $1 WHERE id = $2;"; const updateToValues = [amount, to]; await client.query(updateToBalanceStatement, updateToValues, callback); const selectBalanceStatement = "SELECT id, balance FROM accounts;"; await client.query(selectBalanceStatement, callback); } // This function deletes the third row in the accounts table. async function deleteAccounts(client, callback) { const deleteStatement = "DELETE FROM accounts WHERE id = $1;"; await client.query(deleteStatement, [accountValues[2]], callback); const selectBalanceStatement = "SELECT id, balance FROM accounts;"; await client.query(selectBalanceStatement, callback); } // Run the transactions in the connection pool (async () => { const connectionString = process.env.DATABASE_URL; const pool = new Pool({ connectionString, application_name: "$ docs_simplecrud_node-postgres", }); // Connect to database const client = await pool.connect(); // Callback function cb(err, res) { if (err) throw err; if (res.rows.length > 0) { console.log("New account balances:"); res.rows.forEach((row) => { console.log(row); }); } } // Initialize table in transaction retry wrapper console.log("Initializing accounts table..."); await retryTxn(0, 15, client, initTable, cb); // Transfer funds in transaction retry wrapper console.log("Transferring funds..."); await retryTxn(0, 15, client, transferFunds, cb); // Delete a row in transaction retry wrapper console.log("Deleting a row..."); await retryTxn(0, 15, client, deleteAccounts, cb); // Exit program process.exit(); })().catch((err) => console.log(err.stack)); ``` All of the database operations are wrapped in a helper function named `retryTxn`. This function attempts to commit statements in the context of an explicit transaction. If a [retry error](/docs/v26.4/transaction-retry-error-reference) is thrown, the wrapper will retry committing the transaction, with [exponential backoff](https://wikipedia.org/wiki/Exponential_backoff), until the maximum number of retries is reached (by default, 15). ## Step 3. Initialize the database 1. Navigate to the `example-app-node-postgres` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-node-postgres ``` 2. Set the `DATABASE_URL` environment variable to the connection string for your cluster: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > export DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > export DATABASE_URL="{connection-string}" > ``` > > Where `{connection-string}` is the connection string you copied earlier. 1. To initialize the example database, use the [`cockroach sql`](/docs/v26.4/cockroach-sql) command to execute the SQL statements in the `dbinit.sql` file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cat dbinit.sql | cockroach sql --url $DATABASE_URL ``` The SQL statement in the initialization file should execute: ``` CREATE TABLE Time: 102ms ``` ## Step 4. Run the code 1. Install the app requirements: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ npm install ``` 2. Run the app: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ node app.js ``` The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. The output should look like this: ``` Initializing accounts table... New account balances: { id: 'aa0e9b22-0c23-469b-a9e1-b2ace079f44c', balance: '1000' } { id: 'bf8b96da-2c38-4d55-89a0-b2b6ed63ff9e', balance: '0' } { id: 'e43d76d6-388e-4ee6-8b73-a063a63a2138', balance: '250' } Transferring funds... New account balances: { id: 'aa0e9b22-0c23-469b-a9e1-b2ace079f44c', balance: '900' } { id: 'bf8b96da-2c38-4d55-89a0-b2b6ed63ff9e', balance: '0' } { id: 'e43d76d6-388e-4ee6-8b73-a063a63a2138', balance: '350' } Deleting a row... New account balances: { id: 'aa0e9b22-0c23-469b-a9e1-b2ace079f44c', balance: '900' } { id: 'e43d76d6-388e-4ee6-8b73-a063a63a2138', balance: '350' } ``` ## What's next? Read more about using the [node-postgres driver](https://www.npmjs.com/package/pg). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Simple CRUD Node.js App with CockroachDB and Knex.js Source: https://docs.cockroachlabs.com/docs/stable/build-a-nodejs-app-with-cockroachdb-knexjs This tutorial shows you how build a simple Node.js application with CockroachDB and [Knex.js](https://knexjs.org/). ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_node_knexjs). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-node-knex ``` ## Step 3. Run the code 1. Set the `DATABASE_URL` environment variable to the connection string: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL=" ``` > > Where ` [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_node_prisma). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code 1. Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-node-prisma ``` 2. Install the application dependencies: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-node-prisma ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ npm install ``` ## Step 3. Initialize the database 1. Create a `.env` file for your project, and set the `DATABASE_URL` environment variable to a valid connection string to your cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo "DATABASE_URL=> .env ``` Where `> .env ``` > [!NOTE] > > `postgresql://root@localhost:26257/defaultdb?sslmode=disable` is the `sql` connection string you obtained earlier from the `cockroach` welcome text. Prisma loads the variables defined in `.env` to the project environment. By default, Prisma uses the `DATABASE_URL` environment variable as the connection string to the database. 1. Run [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate) to initialize the database with the schema defined in `prisma/prisma.schema`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ node_modules/.bin/prisma migrate dev --name init ``` You should see the following output: ``` Your database is now in sync with your schema. ✔ Generated Prisma Client (3.12.0 | library) to ./node_modules/@prisma/client in 73ms ``` This command also initializes [Prisma Client](https://www.prisma.io/docs/concepts/components/prisma-client) to communicate with your CockroachDB cluster, based on the configuration in the `prisma/schema.prisma` file. ## Step 4. Run the code The `index.js` file contains the code for `INSERT`, `SELECT`, `UPDATE`, and `DELETE` SQL operations: ```js theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} const { PrismaClient } = require('@prisma/client') const { v4: uuidv4 } = require('uuid') const prisma = new PrismaClient({ datasources: { db: { url: process.env.DATABASE_URL + "&application_name=$ docs_simplecrud_node-prisma", }, }, }) const main = async () => { const customerIds = Array(10).fill().map(() => ({ id: uuidv4() })) const accountValues = Array(10).fill().map((_, index) => ({ id: uuidv4(), customer_id: customerIds[index].id, balance: Math.floor(Math.random() * 1000) })) const insertCustomerRows = await prisma.customer.createMany({ data: customerIds }) console.log('Customer rows inserted.', insertCustomerRows) const insertAccountRows = await prisma.account.createMany({ data: accountValues }) console.log('Account rows inserted.', insertAccountRows) console.log('Initial Account row values:\n', await prisma.account.findMany()) const updateRows = await prisma.account.updateMany({ where: { balance: { gt: 100 } }, data: { balance: { decrement: 5 } } }) console.log('Account rows updated.', updateRows) console.log('Updated Account row values:\n', await prisma.account.findMany()) const deleteAllRows = await prisma.customer.deleteMany() console.log('All Customer rows deleted.', deleteAllRows) } main() .catch((e) => { throw e }) .finally(async () => { await prisma.$disconnect() }) ``` > [!NOTE] > > In [production](/docs/v26.4/recommended-production-settings#transaction-retries), we recommend implementing [client-side retry handling](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling) for all database operations. Run the application code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ node index.js ``` ``` Customer rows inserted. { count: 10 } Account rows inserted. { count: 10 } Initial Account row values: [ { id: '1961432f-f93e-4568-b2a5-ba08f73afde5', customer_id: '079daee3-ecf2-4a0f-980b-4c3ea4c8b6a3', balance: 914n }, { id: '4ccd7eea-eb47-4aa9-9819-30b5aae58bf8', customer_id: 'c0eeb465-ab60-4f02-9bf3-3451578d400d', balance: 176n }, { id: '53ed4f7d-72ee-4390-9487-9bf318357c77', customer_id: 'a4c9e26e-f9d8-4c1b-ac20-1aa8611b134f', balance: 54n }, { id: '79a1f1b2-4050-4329-bf52-5df53fec749e', customer_id: '392c7d15-5ab2-4149-9eee-8a3a44b36e9d', balance: 482n }, { id: '7e30f1e0-e873-4565-9ea3-3079a48a4886', customer_id: '12cb3406-264a-417c-b0e6-86593e60dc18', balance: 478n }, { id: '94f461d5-3985-46c1-98f4-1896f15f0a16', customer_id: 'e4c909a4-6683-429d-9831-dfcf792f4fb0', balance: 240n }, { id: 'a0c081f5-fb15-47cc-8dbb-85c6f15677d2', customer_id: '91ece5f2-df03-4023-b112-2b4d5677981b', balance: 520n }, { id: 'a45b7c41-2f62-4620-be69-57d5d61186e4', customer_id: 'c1824327-d6a1-4916-a666-ea157ef2a409', balance: 50n }, { id: 'dbe0dec5-257b-42ff-9d36-1b5a57e1a4ac', customer_id: '6739eb2f-bcb1-4074-aab4-5860b04d227d', balance: 468n }, { id: 'ebc520b4-8df0-4e2f-8426-104594f6341c', customer_id: 'f83e02cb-77cf-4347-9e0c-28cad65fac34', balance: 336n } ] Account rows updated. { count: 8 } Updated Account row values: [ { id: '1961432f-f93e-4568-b2a5-ba08f73afde5', customer_id: '079daee3-ecf2-4a0f-980b-4c3ea4c8b6a3', balance: 909n }, { id: '4ccd7eea-eb47-4aa9-9819-30b5aae58bf8', customer_id: 'c0eeb465-ab60-4f02-9bf3-3451578d400d', balance: 171n }, { id: '53ed4f7d-72ee-4390-9487-9bf318357c77', customer_id: 'a4c9e26e-f9d8-4c1b-ac20-1aa8611b134f', balance: 54n }, { id: '79a1f1b2-4050-4329-bf52-5df53fec749e', customer_id: '392c7d15-5ab2-4149-9eee-8a3a44b36e9d', balance: 477n }, { id: '7e30f1e0-e873-4565-9ea3-3079a48a4886', customer_id: '12cb3406-264a-417c-b0e6-86593e60dc18', balance: 473n }, { id: '94f461d5-3985-46c1-98f4-1896f15f0a16', customer_id: 'e4c909a4-6683-429d-9831-dfcf792f4fb0', balance: 235n }, { id: 'a0c081f5-fb15-47cc-8dbb-85c6f15677d2', customer_id: '91ece5f2-df03-4023-b112-2b4d5677981b', balance: 515n }, { id: 'a45b7c41-2f62-4620-be69-57d5d61186e4', customer_id: 'c1824327-d6a1-4916-a666-ea157ef2a409', balance: 50n }, { id: 'dbe0dec5-257b-42ff-9d36-1b5a57e1a4ac', customer_id: '6739eb2f-bcb1-4074-aab4-5860b04d227d', balance: 463n }, { id: 'ebc520b4-8df0-4e2f-8426-104594f6341c', customer_id: 'f83e02cb-77cf-4347-9e0c-28cad65fac34', balance: 331n } ] All Customer rows deleted. { count: 10 } ``` ## What's next? Read more about using [Prisma Client](https://www.prisma.io/docs/). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Node.js App with CockroachDB and Sequelize Source: https://docs.cockroachlabs.com/docs/stable/build-a-nodejs-app-with-cockroachdb-sequelize This tutorial shows you how build a simple Node.js application with CockroachDB and the [Sequelize](https://sequelize.org/) ORM. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_node_sequelize). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the sample code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-node-sequelize ``` The sample code uses Sequelize to map Node.js-specific objects to some read and write SQL operations. ## Step 3. Run the code To start the app: 1. Set the `DATABASE_URL` environment variable to the connection string: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL=" ``` > > Where ` [!TIP] > > Check out our developer courses at [Cockroach University](https://university.cockroachlabs.com/). This tutorial shows you how build a simple Python application with CockroachDB and the [psycopg2](https://www.psycopg.org/) driver. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_python_psycopg2). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the root certificate > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > 2. Open a new terminal on your local machine, and run the **CA Cert download command** provided in the **Download CA Cert** section. The client driver used in this tutorial requires this certificate to connect to CockroachDB Cloud. > > > > ### Get the connection string > > > > Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the sample code Clone the sample code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/hello-world-python-psycopg2 ``` The sample code in `example.py` does the following: * Creates an `accounts` table and inserts some rows * Transfers funds between two accounts inside a [transaction](/docs/v26.4/transactions) * Deletes the accounts from the table before exiting so you can re-run the example code To [handle transaction retry errors](/docs/v26.4/query-behavior-troubleshooting#transaction-retry-errors), the code uses an application-level retry loop that, in case of error, sleeps before trying the funds transfer again. If it encounters another retry error, it sleeps for a longer interval, implementing [exponential backoff](https://wikipedia.org/wiki/Exponential_backoff). ## Step 3. Install the psycopg2 driver `psycopg2-binary` is the sample app's only third-party module dependency. To install `psycopg2-binary`, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pip install psycopg2-binary ``` For other ways to install psycopg2, see the [official documentation](http://initd.org/psycopg/docs/install.html). ## Step 4. Run the code 1. Set the `DATABASE_URL` environment variable to the connection string to your cluster: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="{connection-string}" > ``` > > Where `{connection-string}` is the connection string you copied earlier. The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. 1. Run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd hello-world-python-psycopg2 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python example.py ``` The output should show the account balances before and after the funds transfer: ``` Balances at Thu Aug 4 15:51:03 2022: account id: 2e964b45-2034-49a7-8ab8-c5d0082b71f1 balance: $1000 account id: 889cb1eb-b747-46f4-afd0-15d70844147f balance: $250 Balances at Thu Aug 4 15:51:03 2022: account id: 2e964b45-2034-49a7-8ab8-c5d0082b71f1 balance: $900 account id: 889cb1eb-b747-46f4-afd0-15d70844147f balance: $350 ``` ## What's next? Read more about using the [Python psycopg2 driver](https://www.psycopg.org/docs/). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Python App with CockroachDB and asyncpg Source: https://docs.cockroachlabs.com/docs/stable/build-a-python-app-with-cockroachdb-asyncpg > [!TIP] > > Check out our developer courses at [Cockroach University](https://university.cockroachlabs.com/). This tutorial shows you how build a simple Python application with CockroachDB and the [asyncpg](https://magicstack.github.io/asyncpg/current/index.html) driver. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_python_asyncpg). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the root certificate > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > 2. Open a new terminal on your local machine, and run the **CA Cert download command** provided in the **Download CA Cert** section. The client driver used in this tutorial requires this certificate to connect to CockroachDB Cloud. > > > > ### Get the connection string > > > > Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the sample code Clone the sample code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachdb/example-app-python-asyncpg ``` The sample code in `example.py` does the following: * Creates an `accounts` table and inserts some rows * Transfers funds between two accounts inside a [transaction](/docs/v26.4/transactions) * Deletes the accounts from the table before exiting so you can re-run the example code To [handle transaction retry errors](/docs/v26.4/query-behavior-troubleshooting#transaction-retry-errors), the code uses an application-level retry loop that, in case of error, sleeps before trying the funds transfer again. If it encounters another retry error, it sleeps for a longer interval, implementing [exponential backoff](https://wikipedia.org/wiki/Exponential_backoff). ## Step 3. Install the asyncpg driver `asyncpg` is the sample app's only third-party module dependency. To install `asyncpg`, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pip3 install "asyncpg" ``` For other ways to install Psycopg, see the [official documentation](https://www.psycopg.org/psycopg3/docs/basic/install.html). ## Step 4. Run the code 1. Set the `DATABASE_URL` environment variable to the connection string to your cluster: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="{connection-string}" > ``` > > Where `{connection-string}` is the connection string you copied earlier. The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. 1. Run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-python-asyncpg ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python3 example.py ``` The output should show the account balances before and after the funds transfer: ``` Balances at Thu Aug 4 15:51:03 2022: account id: 2e964b45-2034-49a7-8ab8-c5d0082b71f1 balance: $1000 account id: 889cb1eb-b747-46f4-afd0-15d70844147f balance: $250 Balances at Thu Aug 4 15:51:03 2022: account id: 2e964b45-2034-49a7-8ab8-c5d0082b71f1 balance: $900 account id: 889cb1eb-b747-46f4-afd0-15d70844147f balance: $350 ``` > [!NOTE] > > The example code sets the [`multiple_active_portals_enabled` session variable](/docs/v26.4/postgresql-compatibility#multiple-active-portals) to `true`, a requirement for using `asyncpg` with CockroachDB. ## What's next? Read more about using the [asyncpg](https://magicstack.github.io/asyncpg/current/usage.html). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Python App with CockroachDB and Django Source: https://docs.cockroachlabs.com/docs/stable/build-a-python-app-with-cockroachdb-django This tutorial shows you how build a simple Python application with CockroachDB and the [Django](https://www.djangoproject.com/) framework. CockroachDB supports Django versions 3.1+. > [!NOTE] > > The example code and instructions on this page use Python 3.9 and Django 3.1. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_python_django). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the root certificate > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > 2. Open a new terminal on your local machine, and run the **CA Cert download command** provided in the **Download CA Cert** section. The client driver used in this tutorial requires this certificate to connect to CockroachDB Cloud. > > > > ### Get the connection string > > > > Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the sample code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-python-django/ ``` The project directory structure should look like this: ``` ├── Dockerfile ├── README.md ├── cockroach_example │   ├── cockroach_example │   │   ├── __init__.py │   │   ├── asgi.py │   │   ├── migrations │   │   │   ├── 0001_initial.py │   │   │   └── __init__.py │   │   ├── models.py │   │   ├── settings.py │   │   ├── urls.py │   │   ├── views.py │   │   └── wsgi.py │   └── manage.py └── requirements.txt ``` ## Step 3. Install the application requirements To use CockroachDB with Django, the following modules are required: * [`django`](https://docs.djangoproject.com/en/3.1/topics/install/) * [`psycopg2`](https://pypi.org/project/psycopg2/) (recommended for production environments) or [`psycopg2-binary`](https://pypi.org/project/psycopg2-binary/) (recommended for development and testing). * [`django-cockroachdb`](https://github.com/cockroachdb/django-cockroachdb) > [!NOTE] > > The major version of `django-cockroachdb` must correspond to the major version of `django`. The minor release numbers do not need to match. The `requirements.txt` file at the top level of the `example-app-python-django` project directory contains a list of the requirements needed to run this application: ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} psycopg2-binary django==5.0.1 django-cockroachdb==5.0 ``` This tutorial uses [`virtualenv`](https://virtualenv.pypa.io) for dependency management. 1. Install `virtualenv`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pip install virtualenv ``` 2. At the top level of the app's project directory, create and then activate a virtual environment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ virtualenv env ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ source env/bin/activate ``` 3. Install the modules listed in `requirements.txt` to the virtual environment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pip install -r requirements.txt ``` ## Step 4. Build out the application ### Configure the database connection Open `cockroach_example/cockroach_example/settings.py`, and configure [the `DATABASES` dictionary](https://docs.djangoproject.com/en/3.2/ref/settings/#databases) to connect to your cluster using the connection parameters that you copied earlier. ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} DATABASES = { 'default': { 'ENGINE': 'django_cockroachdb', 'NAME': '{database}', 'USER': '{username}', 'PASSWORD': '{password}', 'HOST': '{host}', 'PORT': '{port}', 'OPTIONS': { 'sslmode': 'verify-full' }, }, } ``` For more information about configuration a Django connection to CockroachDB Standard, see [Connect to a CockroachDB Cluster](/docs/v26.4/connect-to-the-database?filters=python\&filters=django). After you have configured the app's database connection, you can start building out the application. ### Models Start by building some [models](https://docs.djangoproject.com/en/3.1/topics/db/models/), defined in a file called `models.py`. You can copy the sample code below and paste it into a new file, or you can download the file directly. ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} from django.db import models class Customers(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) class Products(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) price = models.DecimalField(max_digits=18, decimal_places=2) class Orders(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) subtotal = models.DecimalField(max_digits=18, decimal_places=2) customer = models.ForeignKey( Customers, on_delete=models.CASCADE, null=True) product = models.ManyToManyField(Products) ``` In this file, we define some simple classes that map to the tables in the cluster. ### Views Next, build out some [class-based views](https://docs.djangoproject.com/en/3.1/topics/class-based-views/) for the application in a file called `views.py`. You can copy the sample code below and paste it into a new file, or you can download the file directly. ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} from django.http import JsonResponse, HttpResponse from django.utils.decorators import method_decorator from django.views.generic import View from django.views.decorators.csrf import csrf_exempt from django.db import Error, IntegrityError from django.db.transaction import atomic from psycopg2 import errorcodes from .models import * # Warning: Do not use retry_on_exception in an inner nested transaction. def retry_on_exception(num_retries=3, on_failure=HttpResponse(status=500), delay_=0.5, backoff_=1.5): def retry(view): def wrapper(*args, **kwargs): delay = delay_ for i in range(num_retries): try: return view(*args, **kwargs) except IntegrityError as ex: if i == num_retries - 1: return on_failure elif getattr(ex.__cause__, 'pgcode', '') == errorcodes.SERIALIZATION_FAILURE: time.sleep(delay) delay *= backoff_ except Error as ex: return on_failure return wrapper return retry class PingView(View): def get(self, request, *args, **kwargs): return HttpResponse("python/django", status=200) @method_decorator(csrf_exempt, name='dispatch') class CustomersView(View): def get(self, request, id=None, *args, **kwargs): if id is None: customers = list(Customers.objects.values()) else: customers = list(Customers.objects.filter(id=id).values()) return JsonResponse(customers, safe=False) @retry_on_exception(3) @atomic def post(self, request, *args, **kwargs): form_data = json.loads(request.body.decode()) name = form_data['name'] c = Customers(name=name) c.save() return HttpResponse(status=200) @retry_on_exception(3) @atomic def delete(self, request, id=None, *args, **kwargs): if id is None: return HttpResponse(status=404) Customers.objects.filter(id=id).delete() return HttpResponse(status=200) # The PUT method is shadowed by the POST method, so there doesn't seem # to be a reason to include it. @method_decorator(csrf_exempt, name='dispatch') class ProductView(View): def get(self, request, id=None, *args, **kwargs): if id is None: products = list(Products.objects.values()) else: products = list(Products.objects.filter(id=id).values()) return JsonResponse(products, safe=False) @retry_on_exception(3) @atomic def post(self, request, *args, **kwargs): form_data = json.loads(request.body.decode()) name, price = form_data['name'], form_data['price'] p = Products(name=name, price=price) p.save() return HttpResponse(status=200) # The REST API outlined in the github does not say that /product/ needs # a PUT and DELETE method @method_decorator(csrf_exempt, name='dispatch') class OrdersView(View): def get(self, request, id=None, *args, **kwargs): if id is None: orders = list(Orders.objects.values()) else: orders = list(Orders.objects.filter(id=id).values()) return JsonResponse(orders, safe=False) @retry_on_exception(3) @atomic def post(self, request, *args, **kwargs): form_data = json.loads(request.body.decode()) c = Customers.objects.get(id=form_data['customer']['id']) o = Orders(subtotal=form_data['subtotal'], customer=c) o.save() for p in form_data['products']: p = Products.objects.get(id=p['id']) o.product.add(p) o.save() return HttpResponse(status=200) ``` This file defines the application's views as classes. Each view class corresponds to one of the table classes defined in `models.py`. The methods of these classes define read and write transactions on the tables in the database. Importantly, the file defines a [transaction retry loop](/docs/v26.4/transactions#transaction-retries) in the decorator function `retry_on_exception()`. This function decorates each view method, ensuring that transaction ordering guarantees meet the ANSI [SERIALIZABLE](https://wikipedia.org/wiki/Isolation_\(database_systems\)#Serializable) isolation level. For more information about how transactions (and retries) work, see [Transactions](/docs/v26.4/transactions). ### URL routes Lastly, define some [URL routes](https://docs.djangoproject.com/en/3.1/topics/http/urls/) in a file called `urls.py`. You can copy the sample code below and paste it into the existing `urls.py` file, or you can download the file directly and replace the existing one. ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} from django.contrib import admin from django.urls import path from .views import CustomersView, OrdersView, PingView, ProductView urlpatterns = [ path('admin/', admin.site.urls), path('ping/', PingView.as_view()), # Endpoints for customers URL. path('customer/', CustomersView.as_view(), name='customers'), path('customer/ SELECT * FROM cockroach_example_customers; ``` ``` id | name ---------------------------------------+------- bb7d6c4d-efb3-45f8-b790-9911aae7d8b2 | Carl (1 row) ``` 4. Enter **Ctrl+C** to stop the application. ## What's next? Read more about writing a [Django app](https://docs.djangoproject.com/en/3.1/intro/tutorial01/). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Python App with CockroachDB and Psycopg 3 Source: https://docs.cockroachlabs.com/docs/stable/build-a-python-app-with-cockroachdb-psycopg3 > [!TIP] > > Check out our developer courses at [Cockroach University](https://university.cockroachlabs.com/). This tutorial shows you how build a simple Python application with CockroachDB and the [Psycopg 3](https://www.psycopg.org/) driver. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_python_psycopg3). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the root certificate > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > 2. Open a new terminal on your local machine, and run the **CA Cert download command** provided in the **Download CA Cert** section. The client driver used in this tutorial requires this certificate to connect to CockroachDB Cloud. > > > > ### Get the connection string > > > > Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the sample code Clone the sample code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachdb/example-app-python-psycopg3 ``` The sample code in `example.py` does the following: * Creates an `accounts` table and inserts some rows * Transfers funds between two accounts inside a [transaction](/docs/v26.4/transactions) * Deletes the accounts from the table before exiting so you can re-run the example code To [handle transaction retry errors](/docs/v26.4/query-behavior-troubleshooting#transaction-retry-errors), the code uses an application-level retry loop that, in case of error, sleeps before trying the funds transfer again. If it encounters another retry error, it sleeps for a longer interval, implementing [exponential backoff](https://wikipedia.org/wiki/Exponential_backoff). ## Step 3. Install the Psycopg 3 driver `psycopg[binary]` is the sample app's only third-party module dependency. To install `psycopg[binary]`, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pip3 install "psycopg[binary]" ``` For other ways to install Psycopg, see the [official documentation](https://www.psycopg.org/psycopg3/docs/basic/install.html). ## Step 4. Run the code 1. Set the `DATABASE_URL` environment variable to the connection string to your cluster: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="{connection-string}" > ``` > > Where `{connection-string}` is the connection string you copied earlier. The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. 1. Run the code: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-python-psycopg3 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python3 example.py ``` The output should show the account balances before and after the funds transfer: ``` Balances at Thu Aug 4 15:51:03 2022: account id: 2e964b45-2034-49a7-8ab8-c5d0082b71f1 balance: $1000 account id: 889cb1eb-b747-46f4-afd0-15d70844147f balance: $250 Balances at Thu Aug 4 15:51:03 2022: account id: 2e964b45-2034-49a7-8ab8-c5d0082b71f1 balance: $900 account id: 889cb1eb-b747-46f4-afd0-15d70844147f balance: $350 ``` ## What's next? Read more about using the [Python psycopg3 driver](https://www.psycopg.org/docs/). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Simple CRUD Python App with CockroachDB and SQLAlchemy Source: https://docs.cockroachlabs.com/docs/stable/build-a-python-app-with-cockroachdb-sqlalchemy > [!TIP] > > Check out our developer courses at [Cockroach University](https://university.cockroachlabs.com/). This tutorial shows you how build a simple CRUD Python application with CockroachDB and the [SQLAlchemy](https://docs.sqlalchemy.org/) ORM. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_python_sqlalchemy). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the root certificate > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > 2. Open a new terminal on your local machine, and run the **CA Cert download command** provided in the **Download CA Cert** section. The client driver used in this tutorial requires this certificate to connect to CockroachDB Cloud. > > > > ### Get the connection string > > > > Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachlabs/example-app-python-sqlalchemy/ ``` The project has the following directory structure: ``` ├── README.md ├── dbinit.sql ├── main.py ├── models.py └── requirements.txt ``` The `requirements.txt` file includes the required libraries to connect to CockroachDB with SQLAlchemy, including the [`sqlalchemy-cockroachdb` Python package](https://github.com/cockroachdb/sqlalchemy-cockroachdb), which accounts for some differences between CockroachDB and PostgreSQL: ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} psycopg2-binary sqlalchemy sqlalchemy-cockroachdb ``` The `dbinit.sql` file initializes the database schema that the application uses: ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE TABLE accounts ( id UUID PRIMARY KEY, balance INT8 ); ``` The `models.py` uses SQLAlchemy to map the `Accounts` table to a Python object: ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} from sqlalchemy import Column, Integer from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import declarative_base Base = declarative_base() class Account(Base): """The Account class corresponds to the "accounts" database table. """ __tablename__ = 'accounts' id = Column(UUID(as_uuid=True), primary_key=True) balance = Column(Integer) ``` The `main.py` uses SQLAlchemy to map Python methods to SQL operations: ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} """This simple CRUD application performs the following operations sequentially: 1. Creates 100 new accounts with randomly generated IDs and randomly-computed balance amounts. 2. Chooses two accounts at random and takes half of the money from the first and deposits it into the second. 3. Chooses five accounts at random and deletes them. """ from math import floor from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy_cockroachdb import run_transaction from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from models import Account # The code below inserts new accounts. def create_accounts(session, num): """Create N new accounts with random account IDs and account balances. """ print("Creating new accounts...") new_accounts = [] while num > 0: account_id = uuid.uuid4() account_balance = floor(random.random()*1_000_000) new_accounts.append(Account(id=account_id, balance=account_balance)) seen_account_ids.append(account_id) print(f"Created new account with id {account_id} and balance {account_balance}.") num = num - 1 session.add_all(new_accounts) def transfer_funds_randomly(session, one, two): """Transfer money between two accounts. """ try: source = session.query(Account).filter(Account.id == one).one() except NoResultFound: print("No result was found") except MultipleResultsFound: print("Multiple results were found") dest = session.query(Account).filter(Account.id == two).first() print(f"Random account balances:\nAccount {one}: {source.balance}\nAccount {two}: {dest.balance}") amount = floor(source.balance/2) print(f"Transferring {amount} from account {one} to account {two}...") # Check balance of the first account. if source.balance < amount: raise ValueError(f"Insufficient funds in account {one}") source.balance -= amount dest.balance += amount print(f"Transfer complete.\nNew balances:\nAccount {one}: {source.balance}\nAccount {two}: {dest.balance}") def delete_accounts(session, num): """Delete N existing accounts, at random. """ print("Deleting existing accounts...") delete_ids = [] while num > 0: delete_id = random.choice(seen_account_ids) delete_ids.append(delete_id) seen_account_ids.remove(delete_id) num = num - 1 accounts = session.query(Account).filter(Account.id.in_(delete_ids)).all() for account in accounts: print(f"Deleted account {account.id}.") session.delete(account) if __name__ == '__main__': # For cockroach demo: # DATABASE_URL=postgresql://demo: [!NOTE] > > The example application uses the general connection string, which begins with `postgresql://` but modifies it so it uses the `cockroachdb://` prefix. It does this so SQLAlchemy will use the CockroachDB SQLAlchemy adapter. ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} db_uri = os.environ['DATABASE_URL'].replace("postgresql://", "cockroachdb://") ``` Run the app: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python main.py ``` The application will connect to CockroachDB, and then perform some simple row inserts, updates, and deletes. The output should look something like the following: ``` Creating new accounts... Created new account with id 3a8b74c8-6a05-4247-9c60-24b46e3a88fd and balance 248835. Created new account with id c3985926-5b77-4c6d-a73d-7c0d4b2a51e7 and balance 781972. ... Created new account with id 7b41386c-11d3-465e-a2a0-56e0dcd2e7db and balance 984387. Random account balances: Account 7ad14d02-217f-48ca-a53c-2c3a2528a0d9: 800795 Account 4040aeba-7194-4f29-b8e5-a27ed4c7a297: 149861 Transferring 400397 from account 7ad14d02-217f-48ca-a53c-2c3a2528a0d9 to account 4040aeba-7194-4f29-b8e5-a27ed4c7a297... Transfer complete. New balances: Account 7ad14d02-217f-48ca-a53c-2c3a2528a0d9: 400398 Account 4040aeba-7194-4f29-b8e5-a27ed4c7a297: 550258 Deleting existing accounts... Deleted account 41247e24-6210-4032-b622-c10b3c7222de. Deleted account 502450e4-6daa-4ced-869c-4dff62dc52de. Deleted account 6ff06ef0-423a-4b08-8b87-48af2221bc18. Deleted account a1acb134-950c-4882-9ac7-6d6fbdaaaee1. Deleted account e4f33c55-7230-4080-b5ac-5dde8a7ae41d. ``` In a SQL shell connected to the cluster, you can verify that the rows were inserted, updated, and deleted successfully: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT COUNT(*) FROM accounts; ``` ``` count --------- 95 (1 row) ``` ## Best practices ### Use the `run_transaction` function We strongly recommend using the [`sqlalchemy_cockroachdb.run_transaction()`](https://github.com/cockroachdb/sqlalchemy-cockroachdb/blob/master/sqlalchemy_cockroachdb/transaction.py) function as shown in the code samples on this page. This abstracts the details of [transaction retries](/docs/v26.4/transactions#transaction-retries) away from your application code. Transaction retries are more frequent in CockroachDB than in some other databases because we use [optimistic concurrency control](https://wikipedia.org/wiki/Optimistic_concurrency_control) rather than locking. Because of this, a CockroachDB transaction may have to be tried more than once before it can commit. This is part of how we ensure that our transaction ordering guarantees meet the ANSI [SERIALIZABLE](https://wikipedia.org/wiki/Isolation_\(database_systems\)#Serializable) isolation level. In addition to the above, using `run_transaction` has the following benefits: * Because it must be passed a [sqlalchemy.orm.session.sessionmaker](https://docs.sqlalchemy.org/orm/session_api.html#session-and-sessionmaker) object (*not* a [session][session]), it ensures that a new session is created exclusively for use by the callback, which protects you from accidentally reusing objects via any sessions created outside the transaction. * It abstracts away the [client-side transaction retry logic](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling) from your application, which keeps your application code portable across different databases. For example, the sample code given on this page works identically when run against PostgreSQL (modulo changes to the prefix and port number in the connection string). For more information about how transactions (and retries) work, see [Transactions](/docs/v26.4/transactions). ### Avoid mutations of session and/or transaction state inside `run_transaction()` In general, this is in line with the recommendations of the [SQLAlchemy FAQs](https://docs.sqlalchemy.org/orm/session_basics.html#session-frequently-asked-questions), which state (with emphasis added by the original author) that > As a general rule, the application should manage the lifecycle of the session *externally* to functions that deal with specific data. This is a fundamental separation of concerns which keeps data-specific operations agnostic of the context in which they access and manipulate that data. and > Keep the lifecycle of the session (and usually the transaction) **separate and external**. In keeping with the above recommendations from the official docs, we **strongly recommend** avoiding any explicit mutations of the transaction state inside the callback passed to `run_transaction`, since that will lead to breakage. Specifically, do not make calls to the following functions from inside `run_transaction`: * [`sqlalchemy.orm.Session.commit()`](https://docs.sqlalchemy.org/orm/session_api.html?highlight=commit#sqlalchemy.orm.session.Session.commit) (or other variants of `commit()`): This is not necessary because `cockroachdb.sqlalchemy.run_transaction` handles the savepoint/commit logic for you. * [`sqlalchemy.orm.Session.rollback()`](https://docs.sqlalchemy.org/orm/session_api.html?highlight=rollback#sqlalchemy.orm.session.Session.rollback) (or other variants of `rollback()`): This is not necessary because `cockroachdb.sqlalchemy.run_transaction` handles the commit/rollback logic for you. * [`Session.flush()`][session.flush]: This will not work as expected with CockroachDB because CockroachDB does not support nested transactions, which are necessary for `Session.flush()` to work properly. If the call to `Session.flush()` encounters an error and aborts, it will try to rollback. This will not be allowed by the currently-executing CockroachDB transaction created by `run_transaction()`, and will result in an error message like the following: `sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3)`. ### Break up large transactions into smaller units of work If you see an error message like `transaction is too large to complete; try splitting into pieces`, you are trying to commit too much data in a single transaction. As described in our [Cluster Settings](/docs/v26.4/cluster-settings) docs, the size limit for transactions is defined by the `kv.transaction.max_intents_bytes` setting, which defaults to 256 KiB. Although this setting can be changed by an admin, we strongly recommend against it in most cases. Instead, we recommend breaking your transaction into smaller units of work (or "chunks"). A pattern that works for inserting large numbers of objects using `run_transaction` to handle retries automatically for you is shown below. ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} from sqlalchemy import create_engine, Column, Float, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from cockroachdb.sqlalchemy import run_transaction from random import random Base = declarative_base() # The code below assumes you have run the following SQL statements. # CREATE DATABASE pointstore; # USE pointstore; # CREATE TABLE points ( # id INT PRIMARY KEY DEFAULT unique_rowid(), # x FLOAT NOT NULL, # y FLOAT NOT NULL, # z FLOAT NOT NULL # ); engine = create_engine( # For cockroach demo: 'cockroachdb:// [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_ruby_pg). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone [the code's GitHub repository](https://github.com/cockroachlabs/hello-world-ruby-pg). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} git clone https://github.com/cockroachlabs/hello-world-ruby-pg ``` The code connects as the user you created and executes some basic SQL statements: creating a table, inserting rows, and reading and printing the rows. ## Step 3. Configure the dependencies 1. Install `libpq` for your platform. For example, to install `libpq` on macOS with Homebrew, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} brew install libpq ``` 2. Configure `bundle` to use `libpq`. For example, if you installed `libpq` on macOS with Homebrew, run the following command from the `hello-world-ruby-pg` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} bundle config --local build.pg --with-opt-dir="{libpq-path}" ``` Where `{libpq-path}` is the full path to the `libpq` installation on your machine (e.g., `/usr/local/opt/libpq`). 3. Install the dependencies: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} bundle install ``` ## Step 4. Run the code 1. Set the `DATABASE_URL` environment variable to the connection string to your CockroachDB Cloud cluster: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="{connection-string}" > ``` > > Where `{connection-string}` is the connection string you copied earlier. The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. 1. Run the code to create a table and insert some rows: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ruby main.rb ``` The output should look similar to the following: ``` ------------------------------------------------ print_balances(): Balances as of '2021-02-23 11:56:54 -0800': {"id"=>"1", "balance"=>"1000"} {"id"=>"2", "balance"=>"250"} ------------------------------------------------ transfer_funds(): Trying to transfer 100 from account 1 to account 2 ------------------------------------------------ print_balances(): Balances as of '2021-02-23 11:56:55 -0800': {"id"=>"1", "balance"=>"900"} {"id"=>"2", "balance"=>"350"} ``` ## What's next? Read more about using the [Ruby pg driver](https://rubygems.org/gems/pg). You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Ruby App with CockroachDB and Active Record Source: https://docs.cockroachlabs.com/docs/stable/build-a-ruby-app-with-cockroachdb-activerecord This tutorial shows you how build a simple Ruby application with CockroachDB and [Active Record](http://guides.rubyonrails.org/active_record_basics.html). CockroachDB provides an Active Record adapter for CockroachDB as a [RubyGem](https://rubygems.org/gems/activerecord-cockroachdb-adapter). > [!TIP] > > For a more realistic use of Active Record with CockroachDB in a Rails app, see our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_ruby_activerecord). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone [the code's GitHub repository](https://github.com/cockroachlabs/example-app-ruby-activerecord). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} git clone https://github.com/cockroachlabs/example-app-ruby-activerecord ``` ## Step 3. Configure the dependencies 1. Install `libpq` for your platform. For example, to install `libpq` on macOS with Homebrew, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} brew install libpq ``` 2. Configure `bundle` to use `libpq`. For example, if you installed `libpq` on macOS with Homebrew, run the following command from the `example-app-ruby-activerecord` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} bundle config --local build.pg --with-opt-dir="{libpq-path}" ``` Where `{libpq-path}` is the full path to the `libpq` installation on your machine (e.g., `/usr/local/opt/libpq`). 3. Install the dependencies: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} bundle install ``` ## Step 4. Run the code 1. Set the `DATABASE_URL` environment variable to the connection string to your CockroachDB Cloud cluster: > [tab] Local Cluster > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" > ``` > [tab] CockroachDB Cloud > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ export DATABASE_URL="{connection-string}" > ``` > > Where `{connection-string}` is the connection string you copied earlier. The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. 1. Run the code to create a table and insert some rows: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ruby main.rb ``` The output should be similar to the following: ``` -- create_table(:accounts, {:force=>true, :id=>:integer}) -> 0.1998s account: 1 balance: 1000 account: 2 balance: 250 ``` ## What's next? Read more about using [Active Record](http://guides.rubyonrails.org/active_record_basics.html), or check out a more realistic implementation of Active Record with CockroachDB in a Rails app in our [`examples-orms`](https://github.com/cockroachdb/examples-orms) repository. You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Rust App with CockroachDB and the Rust-Postgres Driver Source: https://docs.cockroachlabs.com/docs/stable/build-a-rust-app-with-cockroachdb This tutorial shows you how build a simple Rust application with CockroachDB and the [Rust-Postgres driver](https://github.com/sfackler/rust-postgres). ## Before you begin You must have Rust and Cargo installed. For instructions on installing Rust and Cargo, see the [Cargo documentation](https://doc.rust-lang.org/cargo/getting-started/installation.html). ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_rust). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code Clone the code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone https://github.com/cockroachdb/example-app-rust-postgres ``` The project has the following structure: ``` ├── Cargo.toml ├── LICENSE ├── README.md └── src └── main.rs ``` The `Cargo.toml` file is the configuration file for the example, and sets the dependencies for the project. ```toml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} [package] name = "bank" version = "0.1.0" edition = "2021" [dependencies] openssl = "0.10.41" postgres-openssl = "0.5.0" chrono = "0.4.22" [dependencies.postgres] version = "0.19.3" features = [ "with-uuid-1" ] [dependencies.uuid] version = "1.1.2" ``` The `main` function is the entry point for the application, with the code for connecting to the cluster, creating the `accounts` table, creating accounts in that table, and transferring money between two accounts. The `execute_txn` function wraps database operations in the context of an explicit transaction. If a [retry error](/docs/v26.4/transaction-retry-error-reference) is thrown, the function will retry committing the transaction, with [exponential backoff](https://wikipedia.org/wiki/Exponential_backoff), until the maximum number of retries is reached (by default, 15). > [!NOTE] > > CockroachDB may require the [client to retry a transaction](/docs/v26.4/transactions#transaction-retries) in case of read/write [contention](/docs/v26.4/performance-best-practices-overview#transaction-contention). CockroachDB provides a generic **retry function** that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code. ```rust theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} /// Runs op inside a transaction and retries it as needed. /// On non-retryable failures, the transaction is aborted and /// rolled back; on success, the transaction is committed. fn execute_txn(client: &mut Client, op: F) -> Result where F: Fn(&mut Transaction) -> Result, { let mut txn = client.transaction()?; loop { // Set a retry savepoint // See https://www.cockroachlabs.com/docs/stable/advanced-client-side-transaction-retries let mut sp = txn.savepoint("cockroach_restart")?; match op(&mut sp).and_then(|t| sp.commit().map(|_| t)) { Err(ref err) if err .code() .map(|e| *e == SqlState::T_R_SERIALIZATION_FAILURE) .unwrap_or(false) => {} r => break r, } } .and_then(|t| txn.commit().map(|_| t)) } ``` The `transfer_funds` function calls `execute_txn` to perform the actual transfer of funds from one account to the other. ```rust theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} fn transfer_funds(txn: &mut Transaction, from: Uuid, to: Uuid, amount: i64) -> Result<(), Error> { // Read the balance. let from_balance: i64 = txn .query_one("SELECT balance FROM accounts WHERE id = $1", &[&from])? .get(0); assert!(from_balance >= amount); // Perform the transfer. txn.execute( "UPDATE accounts SET balance = balance - $1 WHERE id = $2", &[&amount, &from], )?; txn.execute( "UPDATE accounts SET balance = balance + $1 WHERE id = $2", &[&amount, &to], )?; Ok(()) } ``` ## Step 3. Run the code 1. In a terminal go to the `example-app-rust-postgres` directory. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cd example-app-rust-postgres ``` 2. Set the `DATABASE_URL` environment variable to the connection string to your CockroachDB Cloud cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" ``` 1. Edit the connection string you copied earlier and replace `sslmode=verify-full` with `sslmode=require`. > [!CAUTION] > > You **must** change the `sslmode` in your connection string to `sslmode=require`, as the Rust `postgres` driver does not recognize `sslmode=verify-full`. This example uses `postgres-openssl`, which will perform host verification when the `sslmode=require` option is set, so `require` is functionally equivalent to `verify-full`. For example: ``` postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/bank?sslmode=require ``` 1. Set the `DATABASE_URL` environment variable to the modified connection string. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ export DATABASE_URL="{connection-string}" ``` Where `{connection-string}` is the modified connection string. The app uses the connection string saved to the `DATABASE_URL` environment variable to connect to your cluster and execute the code. 1. Run the code to create a table and insert some rows: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cargo run ``` The output should look similar to the following: ``` Compiling bank v0.1.0 (/Users/maxroach/go/src/github.com/cockroachdb/example-app-rust-postgres) Finished dev [unoptimized + debuginfo] target(s) in 8.00s Running `target/debug/bank` Creating accounts table if it doesn't already exist. Deleted existing accounts. Balances before transfer: account id: 8e88f765-b532-4071-a23d-1b33729d01cb balance: $250 account id: c6de70e2-78e0-484b-ae5b-6ac2aa43d9ec balance: $1000 Final balances: account id: 8e88f765-b532-4071-a23d-1b33729d01cb balance: $350 account id: c6de70e2-78e0-484b-ae5b-6ac2aa43d9ec balance: $900 ``` ## What's next? Read more about using the Rust-Postgres driver. You might also be interested in the following pages: * [Client Connection Parameters](connection-parameters) * [Connection Pooling](connection-pooling) * [Data Replication](demo-replication-and-rebalancing) * [CockroachDB Resilience](demo-cockroachdb-resilience) * [Replication & Rebalancing](demo-replication-and-rebalancing) # Build a Spring App with CockroachDB and MyBatis Source: https://docs.cockroachlabs.com/docs/stable/build-a-spring-app-with-cockroachdb-mybatis This tutorial shows you how to build a simple [Spring Boot](https://spring.io/projects/spring-boot) application with CockroachDB, using the [MyBatis-Spring-Boot-Starter module](http://mybatis.org/spring-boot-starter) for data access. ## Before you begin 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac). 2. Start up a [secure](/docs/v26.4/secure-a-cluster) or [insecure](/docs/v26.4/start-a-local-cluster) local cluster. 3. Choose the instructions that correspond to whether your cluster is secure or insecure: > [!CAUTION] > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 1. Install JDK Download and install a Java Development Kit. MyBatis-Spring supports Java versions 8+. In this tutorial, we use [JDK 11 from OpenJDK](https://openjdk.java.net/install/). ## Step 2. Install Gradle This example application uses [Gradle](https://gradle.org/) to manage all application dependencies. Spring supports Gradle versions 6+. To install Gradle on macOS, run the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ brew install gradle ``` To install Gradle on a Debian-based Linux distribution like Ubuntu: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ apt-get install gradle ``` To install Gradle on a Red Hat-based Linux distribution like Fedora: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ dnf install gradle ``` For other ways to install Gradle, see [its official documentation](https://docs.gradle.org/current/userguide/installation.html). ## Step 3. Get the application code To get the application code, download or clone the [`mybatis-cockroach-demo` repository](https://github.com/jeffgbutler/mybatis-cockroach-demo). ## Step 4. Create the `maxroach` user and `bank` database > [tab] Secure > > Start the [built-in SQL shell](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --certs-dir=certs > ``` > > In the SQL shell, issue the following statements to create the `maxroach` user and `bank` database: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER IF NOT EXISTS maxroach; > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > Give the `bank` user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO maxroach; > ``` > > Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > > ## Step 5. Generate a certificate for the `maxroach` user > > Create a certificate and key for the `maxroach` user by running the following command. The code samples will run as this user. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach cert create-client maxroach --certs-dir=certs --ca-key=my-safe-directory/ca.key --also-generate-pkcs8-key > ``` > > The [`--also-generate-pkcs8-key` flag](/docs/v26.4/cockroach-cert#flag-pkcs8) generates a key in [PKCS#8 format](https://tools.ietf.org/html/rfc5208), which is the standard key encoding format in Java. In this case, the generated PKCS8 key will be named `client.maxroach.key.pk8`. > > ## Step 6. Run the application > > To run the application: > > 1. Open and edit the `src/main/resources/application.yml` file so that the `url` field specifies the full [connection string](/docs/v26.4/connection-parameters#connect-using-a-url) to the [running CockroachDB cluster](#before-you-begin). To connect to a secure cluster, this connection string must set the `sslmode` connection parameter to `require`, and specify the full path to the client, node, and user certificates in the connection parameters. For example: > > ```yml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ... > datasource: > url: jdbc:postgresql://localhost:26257/bank?ssl=true&sslmode=require&sslrootcert=certs/ca.crt&sslkey=certs/client.maxroach.key.pk8&sslcert=certs/client.maxroach.crt > ... > ``` > > 2. Open a terminal, and navigate to the `mybatis-cockroach-demo` project directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cd /mybatis-cockroach-demo > ``` > > 3. Run the Gradle script to download the application dependencies, compile the code, and run the application: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ ./gradlew bootRun > ``` > [tab] Insecure > > Start the [built-in SQL shell](/docs/v26.4/cockroach-sql): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --insecure > ``` > > In the SQL shell, issue the following statements to create the `maxroach` user and `bank` database: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE USER IF NOT EXISTS maxroach; > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > CREATE DATABASE bank; > ``` > > Give the `bank` user the necessary permissions: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > GRANT ALL ON DATABASE bank TO maxroach; > ``` > > Exit the SQL shell: > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > \q > ``` > > ## Step 5. Run the application > > To run the application: > > 1. Open and edit the `src/main/resources/application.yml` file so that the `url` field specifies the full [connection string](/docs/v26.4/connection-parameters#connect-using-a-url) to the [running CockroachDB cluster](#before-you-begin). For example: > > ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ... > datasource: > url: jdbc:postgresql://localhost:26257/bank?ssl=false > ... > ``` > > 2. Open a terminal, and navigate to the `mybatis-cockroach-demo` project directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cd /mybatis-cockroach-demo > ``` > > 3. Run the Gradle script to download the application dependencies, compile the code, and run the application: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ ./gradlew bootRun > ``` The output should look like the following: ``` > Task :bootRun . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.6.RELEASE) 2020-06-01 14:40:04.333 INFO 55970 --- [ main] c.e.c.CockroachDemoApplication : Starting CockroachDemoApplication on MyComputer with PID 55970 (path/mybatis-cockroach-demo/build/classes/java/main started by user in path/mybatis-cockroach-demo) 2020-06-01 14:40:04.335 INFO 55970 --- [ main] c.e.c.CockroachDemoApplication : No active profile set, falling back to default profiles: default 2020-06-01 14:40:05.195 INFO 55970 --- [ main] c.e.c.CockroachDemoApplication : Started CockroachDemoApplication in 1.39 seconds (JVM running for 1.792) 2020-06-01 14:40:05.216 INFO 55970 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2020-06-01 14:40:05.611 INFO 55970 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. deleteAllAccounts: => 2 total deleted accounts insertAccounts: => 2 total new accounts in 1 batches printNumberOfAccounts: => Number of accounts at time '14:40:05.660226': => 2 total accounts printBalances: => Account balances at time '14:40:05.678942': ID 1 => $1000 ID 2 => $250 transferFunds: => $100 transferred between accounts 1 and 2, 2 rows updated printBalances: => Account balances at time '14:40:05.688511': ID 1 => $900 ID 2 => $350 bulkInsertRandomAccountData: => finished, 500 total rows inserted in 1 batches printNumberOfAccounts: => Number of accounts at time '14:40:05.960214': => 502 total accounts 2020-06-01 14:40:05.968 INFO 55970 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2020-06-01 14:40:05.993 INFO 55970 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. BUILD SUCCESSFUL in 12s 3 actionable tasks: 3 executed ``` The application runs a number of test functions that result in reads and writes to the `accounts` table in the `bank` database. For more details about the application code, see [Application details](#application-details). ## Application details This section guides you through the different components of the application project in detail. ### Main process The main process of the application is defined in `src/main/java/com/example/cockroachdemo/CockroachDemoApplication.java`: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CockroachDemoApplication { public static void main(String[] args) { SpringApplication.run(CockroachDemoApplication.class, args); } } ``` The `SpringApplication.run` call in the `main` method bootstraps and launches a Spring application. The [`@SpringBootApplication` annotation](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-using-springbootapplication-annotation) on the `CockroachDemoApplication` class triggers Spring's [component scanning](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-structuring-your-code) and [auto-configuration](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-auto-configuration) features. The `BasicExample` class, defined in `src/main/java/com/example/cockroachdemo/BasicExample.java`, is one of the components detected in the component scan: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo; import java.time.LocalTime; import com.example.cockroachdemo.model.Account; import com.example.cockroachdemo.model.BatchResults; import com.example.cockroachdemo.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("!test") public class BasicExample implements CommandLineRunner { @Autowired private AccountService accountService; @Override public void run(String... args) throws Exception { accountService.createAccountsTable(); deleteAllAccounts(); insertAccounts(); printNumberOfAccounts(); printBalances(); transferFunds(); printBalances(); bulkInsertRandomAccountData(); printNumberOfAccounts(); } private void deleteAllAccounts() { int numDeleted = accountService.deleteAllAccounts(); System.out.printf("deleteAllAccounts:\n => %s total deleted accounts\n", numDeleted); } private void insertAccounts() { Account account1 = new Account(); account1.setId(1); account1.setBalance(1000); Account account2 = new Account(); account2.setId(2); account2.setBalance(250); BatchResults results = accountService.addAccounts(account1, account2); System.out.printf("insertAccounts:\n => %s total new accounts in %s batches\n", results.getTotalRowsAffected(), results.getNumberOfBatches()); } private void printBalances() { int balance1 = accountService.getAccount(1).map(Account::getBalance).orElse(-1); int balance2 = accountService.getAccount(2).map(Account::getBalance).orElse(-1); System.out.printf("printBalances:\n => Account balances at time '%s':\n ID %s => $%s\n ID %s => $%s\n", LocalTime.now(), 1, balance1, 2, balance2); } private void printNumberOfAccounts() { System.out.printf("printNumberOfAccounts:\n => Number of accounts at time '%s':\n => %s total accounts\n", LocalTime.now(), accountService.findCountOfAccounts()); } private void transferFunds() { int fromAccount = 1; int toAccount = 2; int transferAmount = 100; int transferredAccounts = accountService.transferFunds(fromAccount, toAccount, transferAmount); System.out.printf("transferFunds:\n => $%s transferred between accounts %s and %s, %s rows updated\n", transferAmount, fromAccount, toAccount, transferredAccounts); } private void bulkInsertRandomAccountData() { BatchResults results = accountService.bulkInsertRandomAccountData(500); System.out.printf("bulkInsertRandomAccountData:\n => finished, %s total rows inserted in %s batches\n", results.getTotalRowsAffected(), results.getNumberOfBatches()); } } ``` `BasicExample` implements the [Spring `CommandLineRunner` interface](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-command-line-runner). Implementations of this interface automatically run when detected in a Spring project directory. `BasicExample` runs a series of test methods that are eventually executed as SQL queries in the [data access layer of the application](#mappers). ### Configuration All [MyBatis-Spring](https://mybatis.org/spring/) applications need a [`DataSource`](https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-configure-datasource), a [`SqlSessionFactory`](https://mybatis.org/spring/factorybean.html), and at least one [mapper interface](https://mybatis.org/spring/mappers.html). The [MyBatis-Spring-Boot-Starter](https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure) module, built on [MyBatis](https://mybatis.org/mybatis-3/) and MyBatis-Spring, and used by this application, greatly simplifies how you configure each of these required elements. Applications that use MyBatis-Spring-Boot-Starter typically need just an annotated mapper interface and an existing `DataSource` in the Spring environment. The module detects the `DataSource`, creates a `SqlSessionFactory` from the `DataSource`, creates a thread-safe [`SqlSessionTemplate`](https://mybatis.org/spring/sqlsession.html#SqlSessionTemplate) with the `SqlSessionFactory`, and then auto-scans the mappers and links them to the `SqlSessionTemplate` for injection. The `SqlSessionTemplate` automatically commits, rolls back, and closes sessions, based on the application's [Spring-based transaction configuration](https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction). This sample application implements [batch write operations](/docs/v26.4/insert#performance-best-practices), a CockroachDB best practice for executing multiple `INSERT` and `UPSERT` statements. MyBatis applications that support batch operations require some additional configuration work, even if the application uses MyBatis-Spring-Boot-Starter: * The application must define a specific mapper interface for batch query methods. * The application must define a `SqlSessionTemplate` constructor, specifically for batch operations, that uses the [`BATCH` executor type](https://mybatis.org/mybatis-3/apidocs/reference/org/apache/ibatis/executor/BatchExecutor.html). * The batch mapper must be explicitly registered with the batch-specific `SqlSessionTemplate`. The class defined in `src/main/java/com/example/cockroachdemo/MyBatisConfiguration.java` configures the application to meet these requirements: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo; import javax.sql.DataSource; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; /** * This class configures MyBatis and sets up mappers for injection. * * When using the Spring Boot Starter, using a class like this is completely optional unless you need to * have some mappers use the BATCH executor (as we do in this demo). If you don't have that requirement, * then you can remove this class. By Default, the MyBatis Spring Boot Starter will find all mappers * annotated with @Mapper and will automatically wire your Datasource to the underlying MyBatis * infrastructure. */ @Configuration @MapperScan(basePackages = "com.example.cockroachdemo.mapper", annotationClass = Mapper.class) @MapperScan(basePackages = "com.example.cockroachdemo.batchmapper", annotationClass = Mapper.class, sqlSessionTemplateRef = "batchSqlSessionTemplate") public class MyBatisConfiguration { @Autowired private DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); return factory.getObject(); } @Bean @Primary public SqlSessionTemplate sqlSessionTemplate() throws Exception { return new SqlSessionTemplate(sqlSessionFactory()); } @Bean(name = "batchSqlSessionTemplate") public SqlSessionTemplate batchSqlSessionTemplate() throws Exception { return new SqlSessionTemplate(sqlSessionFactory(), ExecutorType.BATCH); } } ``` This class explicitly defines the batch `SqlSessionTemplate` (i.e., `batchSqlSessionTemplate`), and registers `batchmapper`, the batch mapper interface defined in [`src/main/java/com/example/cockroachdemo/batchmapper/BatchMapper.java`](#mappers) with `batchSqlSessionTemplate`. To complete the MyBatis configuration, the class also declares a `DataSource`, and defines the remaining `SqlSessionFactory` and `SqlSessionTemplate` beans. Note that a configuration class is not required for MyBatis-Spring-Boot-Starter applications that do not implement batch operations. ### Data source `src/main/resources/application.yml` contains the metadata used to create a connection to the CockroachDB cluster: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spring: datasource: driver-class-name: org.postgresql.Driver url: jdbc:postgresql://localhost:26257/bank?ssl=false username: maxroach ``` Spring Boot uses the application's `datasource` property [to auto-configure the database connection](https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-configure-datasource). This database connection configuration can be injected into the application's `SqlSessionFactoryBean`, as is explicitly done in the [MyBatisConfiguration](#configuration) configuration class definition. ### Mappers All MyBatis applications require at least one mapper interface. These mappers take the place of manually-defined data access objects (DAOs). They provide other layers of the application an interface to the database. MyBatis-Spring-Boot-Starter usually scans the project for interfaces annotated with `@Mapper`, links the interfaces to a `SqlSessionTemplate`, and registers them with Spring so they can be [injected into the application's Spring beans](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-spring-beans-and-dependency-injection). As mentioned in the [Configuration section](#configuration), because the application supports batch writes, the two mapper interfaces in the application are registered and linked manually in the `MyBatisConfiguration` configuration class definition. #### Account mapper `src/main/java/com/example/cockroachdemo/mapper/AccountMapper.java` defines the mapper interface to the `accounts` table using the [MyBatis Java API](https://mybatis.org/mybatis-3/java-api.html): ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo.mapper; import java.util.List; import java.util.Optional; import com.example.cockroachdemo.model.Account; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; @Mapper public interface AccountMapper { @Delete("delete from accounts") int deleteAllAccounts(); @Update("update accounts set balance=#{balance} where id=${id}") void updateAccount(Account account); @Select("select id, balance from accounts where id=#{id}") Optional findAccountById(int id); @Select("select id, balance from accounts order by id") List findAllAccounts(); @Update({ "upsert into accounts (id, balance) values", "(#{fromId}, ((select balance from accounts where id = #{fromId}) - #{amount})),", "(#{toId}, ((select balance from accounts where id = #{toId}) + #{amount}))", }) int transfer(@Param("fromId") int fromId, @Param("toId") int toId, @Param("amount") int amount); @Update("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT, CONSTRAINT balance_gt_0 CHECK (balance >= 0))") void createAccountsTable(); @Select("select count(*) from accounts") Long findCountOfAccounts(); } ``` The `@Mapper` annotation declares the interface a mapper for MyBatis to scan. The SQL statement annotations on each of the interface methods map them to SQL queries. For example, the first method, `deleteAllAccounts()` is marked as a `DELETE` statement with the `@Delete` annotation. This method executes the SQL statement specified in the string passed to the annotation, "`delete from accounts`", which deletes all rows in the `accounts` table. #### Batch account mapper `src/main/java/com/example/cockroachdemo/batchmapper/BatchAccountMapper.java` defines a mapper interface for [batch writes](/docs/v26.4/insert#performance-best-practices): ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo.batchmapper; import java.util.List; import com.example.cockroachdemo.model.Account; import org.apache.ibatis.annotations.Flush; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.executor.BatchResult; @Mapper public interface BatchAccountMapper { @Insert("upsert into accounts(id, balance) values(#{id}, #{balance})") void insertAccount(Account account); @Flush List flush(); } ``` This interface has a single `INSERT` statement query method, along with a method for flushing (i.e., executing) a batch of statements. ### Services `src/main/java/com/example/cockroachdemo/service/AccountService.java` defines the service interface, with a number of methods for reading and writing to the database: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo.service; import java.util.Optional; import com.example.cockroachdemo.model.Account; import com.example.cockroachdemo.model.BatchResults; public interface AccountService { void createAccountsTable(); Optional getAccount(int id); BatchResults bulkInsertRandomAccountData(int numberToInsert); BatchResults bulkInsertRandomAccountData(int numberToInsert, int batchSize); BatchResults addAccounts(Account...accounts); int transferFunds(int fromAccount, int toAccount, int amount); long findCountOfAccounts(); int deleteAllAccounts(); } ``` `MyBatisAccountService.java` implements the `AccountService` interface, using the mappers defined in [`AccountMapper.java` and `BatchAccountMapper.java`](#mappers), and the models defined in [`Account.java` and `BatchResults.java`](#models): ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Random; import com.example.cockroachdemo.batchmapper.BatchAccountMapper; import com.example.cockroachdemo.mapper.AccountMapper; import com.example.cockroachdemo.model.Account; import com.example.cockroachdemo.model.BatchResults; import org.apache.ibatis.executor.BatchResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class MyBatisAccountService implements AccountService { @Autowired private AccountMapper mapper; @Autowired private BatchAccountMapper batchMapper; private Random random = new Random(); @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void createAccountsTable() { mapper.createAccountsTable(); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public BatchResults addAccounts(Account...accounts) { for (Account account : accounts) { batchMapper.insertAccount(account); } List results = batchMapper.flush(); return new BatchResults(1, calculateRowsAffectedBySingleBatch(results)); } private int calculateRowsAffectedBySingleBatch(List results) { return results.stream() .map(BatchResult::getUpdateCounts) .flatMapToInt(Arrays::stream) .sum(); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public BatchResults bulkInsertRandomAccountData(int numberToInsert) { List> results = new ArrayList<>(); for (int i = 0; i < numberToInsert; i++) { Account account = new Account(); account.setId(random.nextInt(1000000000)); account.setBalance(random.nextInt(1000000000)); batchMapper.insertAccount(account); } results.add(batchMapper.flush()); return new BatchResults(results.size(), calculateRowsAffectedByMultipleBatches(results)); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public BatchResults bulkInsertRandomAccountData(int numberToInsert, int batchSize) { List> results = new ArrayList<>(); for (int i = 0; i < numberToInsert; i++) { Account account = new Account(); account.setId(random.nextInt(1000000000)); account.setBalance(random.nextInt(1000000000)); batchMapper.insertAccount(account); if ((i + 1) % batchSize == 0) { results.add(batchMapper.flush()); } } if(numberToInsert % batchSize != 0) { results.add(batchMapper.flush()); } return new BatchResults(results.size(), calculateRowsAffectedByMultipleBatches(results)); } private int calculateRowsAffectedByMultipleBatches(List> results) { return results.stream() .mapToInt(this::calculateRowsAffectedBySingleBatch) .sum(); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public Optional getAccount(int id) { return mapper.findAccountById(id); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public int transferFunds(int fromId, int toId, int amount) { return mapper.transfer(fromId, toId, amount); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public long findCountOfAccounts() { return mapper.findCountOfAccounts(); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public int deleteAllAccounts() { return mapper.deleteAllAccounts(); } } ``` Note that the public methods (i.e., the methods to be called by other classes in the project) are annotated as [`@Transactional`](https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations) methods. This ensures that all of the SQL statements executed in the data access layer are run within the context of a [database transaction](/docs/v26.4/transactions) `@Transactional` takes a number of parameters, including a `propagation` parameter that determines the transaction propagation behavior around an object (i.e., at what point in the stack a transaction starts and ends). `propagation=REQUIRES_NEW` for the methods in the service layer, meaning that a new transaction must be created each time a request is made to the service layer. With this propagation behavior, the application follows the [entity-control-boundary (ECB) pattern](https://wikipedia.org/wiki/Entity-control-boundary), as the service boundaries determine where a [transaction](/docs/v26.4/transactions) starts and ends rather than the lower-level query methods of the [mapper interfaces](#mappers). For more details on aspect-oriented transaction management in this application, [see below](#transaction-management). ### Models Instances of the `Account` class, defined in `src/main/java/com/example/cockroachdemo/model/Account.java`, represent rows in the `accounts` table: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo.model; public class Account { private int id; private int balance; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } } ``` Instances of the `BatchResults` class, defined in `src/main/java/com/example/cockroachdemo/model/BatchResults.java`, hold metadata about a batch write operation and its results: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo.model; public class BatchResults { private int numberOfBatches; private int totalRowsAffected; public BatchResults(int numberOfBatches, int totalRowsAffected) { this.numberOfBatches = numberOfBatches; this.totalRowsAffected = totalRowsAffected; } public int getNumberOfBatches() { return numberOfBatches; } public int getTotalRowsAffected() { return totalRowsAffected; } } ``` ### Transaction management MyBatis-Spring supports Spring's [declarative, aspect-oriented transaction management syntax](https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative), including the [`@Transactional`](https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations) annotation and [AspectJ's AOP annotations](https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative-aspectj). Transactions may require retries if they experience deadlock or [transaction contention](/docs/v26.4/performance-best-practices-overview#transaction-contention) that cannot be resolved without allowing [serialization](/docs/v26.4/demo-serializable) anomalies. To handle transactions that are aborted due to transient serialization errors, we highly recommend writing [client-side transaction retry logic](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling) into applications written on CockroachDB. In this application, transaction retry logic is written into the methods of the `RetryableTransactionAspect` class, defined in `src/main/java/com/example/cockroachdemo/RetryableTransactionAspect.java`: ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} package com.example.cockroachdemo; import java.lang.reflect.UndeclaredThrowableException; import java.util.concurrent.atomic.AtomicLong; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.dao.TransientDataAccessException; import org.springframework.stereotype.Component; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; /** * Aspect with an around advice that intercepts and retries transient concurrency exceptions. * Methods matching the pointcut expression (annotated with @Transactional) are retried. *

* This advice needs to run in a non-transactional context, which is before the underlying * transaction advisor (@Order ensures that). */ @Component @Aspect // Before TX advisor @Order(Ordered.LOWEST_PRECEDENCE - 1) public class RetryableTransactionAspect { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Pointcut("@annotation(transactional)") public void anyTransactionBoundaryOperation(Transactional transactional) { } @Around(value = "anyTransactionBoundaryOperation(transactional)", argNames = "pjp,transactional") public Object retryableOperation(ProceedingJoinPoint pjp, Transactional transactional) throws Throwable { final int totalRetries = 30; int numAttempts = 0; AtomicLong backoffMillis = new AtomicLong(150); Assert.isTrue(!TransactionSynchronizationManager.isActualTransactionActive(), "TX active"); do { try { numAttempts++; return pjp.proceed(); } catch (TransientDataAccessException | TransactionSystemException ex) { handleTransientException(ex, numAttempts, totalRetries, pjp, backoffMillis); } catch (UndeclaredThrowableException ex) { Throwable t = ex.getUndeclaredThrowable(); if (t instanceof TransientDataAccessException) { handleTransientException(t, numAttempts, totalRetries, pjp, backoffMillis); } else { throw ex; } } } while (numAttempts < totalRetries); throw new ConcurrencyFailureException("Too many transient errors (" + numAttempts + ") for method [" + pjp.getSignature().toLongString() + "]. Giving up!"); } private void handleTransientException(Throwable ex, int numAttempts, int totalAttempts, ProceedingJoinPoint pjp, AtomicLong backoffMillis) { if (logger.isWarnEnabled()) { logger.warn("Transient data access exception (" + numAttempts + " of max " + totalAttempts + ") " + "detected (retry in " + backoffMillis + " ms) " + "in method '" + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() + "': " + ex.getMessage()); } if (backoffMillis.get() >= 0) { try { Thread.sleep(backoffMillis.get()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } backoffMillis.set(Math.min((long) (backoffMillis.get() * 1.5), 1500)); } } } ``` The [`@Aspect` annotation](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-at-aspectj) declares `RetryableTransactionAspect` an [aspect](https://wikipedia.org/wiki/Aspect_\(computer_programming\)), with [pointcut](https://wikipedia.org/wiki/Pointcut) and [advice](https://wikipedia.org/wiki/Advice_\(programming\)) methods. #### Transactional pointcut The [`@Pointcut` annotation](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts) declares the `anyTransactionBoundaryOperation` method the pointcut for determining when to execute the aspect's advice. The `@annotation` [designator](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts-designators) passed to the `@Pointcut` annotation limits the matches (i.e., [join points](https://wikipedia.org/wiki/Join_point)) to method calls with a specific annotation, in this case, `@Transactional`. #### Transaction retry advice `retryableOperation` handles the application retry logic, with [exponential backoff](https://wikipedia.org/wiki/Exponential_backoff), as the advice to execute at an `anyTransactionBoundaryOperation(transactional)` join point. Spring supports [several different annotations to declare advice](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-advice). The [`@Around` annotation](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-ataspectj-around-advice) allows an advice method to work before and after the join point. It also gives the advice method control over executing any other matching advisors. `retryableOperation` first verifies that there is no active transaction. It then increments the retry count and attempts to proceed to the next advice method with the `ProceedingJoinPoint.proceed()` method. If the underlying data access layer method (i.e., the mapper interface method annotated with `@Transactional`) succeeds, the results are returned and the application flow continues. If the method fails, then the transaction is retried. The time between each retry grows with each retry until the maximum number of retries is reached. #### Advice ordering Spring automatically adds [transaction management advice](https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#tx-decl-explained) to all methods annotated with `@Transactional`. Because the pointcut for `RetryableTransactionAspect` also matches methods annotated with `@Transactional`, there will always be two advisors that match the same pointcut. When multiple advisors match at the same pointcut, an `@Order` annotation on an advisor's aspect can specify the order in which the advice should be evaluated. To control when and how often a transaction is retried, the transaction retry advice must be executed outside the context of a transaction (i.e., it must be evaluated before the primary transaction management advisor). By default, the primary transaction management advisor is given the lowest level of precedence. The `@Order` annotation on `RetryableTransactionAspect` is passed `Ordered.LOWEST_PRECEDENCE-1`, which places this aspect's advice at a level of precedence above the primary transaction advisor, which results in the retry logic being evaluated before the transaction management advisor. For more details about advice ordering in Spring, see [Advice Ordering](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-ataspectj-advice-ordering) on the Spring documentation site. ## See also Spring documentation: * [Spring Boot website](https://spring.io/projects/spring-boot) * [Spring Framework Overview](https://docs.spring.io/spring/docs/current/spring-framework-reference/overview.html#overview) * [Spring Core documentation](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#spring-core) * [MyBatis documentation](https://mybatis.org/mybatis-3/) * [MyBatis Spring integration](https://mybatis.org/spring/) CockroachDB documentation: * [Learn CockroachDB SQL](/docs/v26.4/learn-cockroachdb-sql) * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [CockroachDB Developer Guide](/docs/v26.4/developer-basics) * [Transactions](/docs/v26.4/transactions) # Build a TypeScript App with CockroachDB and TypeORM Source: https://docs.cockroachlabs.com/docs/stable/build-a-typescript-app-with-cockroachdb This tutorial shows you how run a simple application built with [TypeORM](https://typeorm.io/#/). ## Step 1. Start CockroachDB > [tab] Use CockroachDB Cloud > > ### Choose your installation method > > You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or `ccloud`, a command-line interface (CLI) tool. > > > [tab] Cloud Console (GUI) > > > > ### Create a free cluster > > > > > [!NOTE] > > > > > > Organizations without billing information on file can only create one CockroachDB Basic cluster. > > > > 1. If you haven't already, [sign up for a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?referralId=docs_typescript). > > 2. [Log in](https://cockroachlabs.cloud/) to your CockroachDB Cloud account. > > 3. On the **Clusters** page, click **Create cluster**. > > 4. On the **Select a plan** page, select **Basic**. > > 5. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS) in the **Cloud provider** section. > > 6. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. > > 7. Click **Next: Capacity**. > > 8. On the **Capacity** page, select **Start for free**. Click **Next: Finalize**. > > 9. On the **Finalize** page, click **Create cluster**. > > > > Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. > > > > ### Create a SQL user > > > > The **Create SQL user** dialog allows you to create a new SQL user and password. > > > > 1. Enter a username in the **SQL user** field or use the one provided by default. > > 2. Click **Generate & save password**. > > 3. Copy the generated password and save it in a secure location. > > 4. Click **Next**. > > > > Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster](/docs/cockroachcloud/managing-access#manage-sql-users-on-a-cluster). > > > > ### Get the connection string > > > > The **Connect to cluster** dialog shows information about how to connect to your cluster. > > > > 1. Select **General connection string** from the **Select option** dropdown. > > > > 2. Open the **General connection string** section, then copy the connection string provided and save it in a secure location. > > > > The sample application used in this tutorial uses system CA certificates for server certificate verification, so you can skip the **Download CA Cert** instructions. > > > > > [!NOTE] > > > > > > The connection string is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided *only once*. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. > > > [tab] ccloud CLI > > > > Follow these steps to create a CockroachDB Basic cluster using the `ccloud` CLI tool. > > > > > [!NOTE] > > > > > > The `ccloud` CLI tool is in Preview. > > > > ### Install `ccloud` > > > > > [tab] Mac > > > > > > You can install `ccloud` using either Homebrew or by downloading the binary. > > > > > > #### Use Homebrew > > > > > > 1. [Install Homebrew](http://brew.sh/). > > > 2. Install using the `ccloud` tap: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > brew install cockroachdb/tap/ccloud > > > ``` > > > > > > #### Download the binary > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-amd64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > > Use the ARM 64 binary if you have an M-series Mac: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_darwin-arm64_.tar.gz | tar -xJ && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Linux > > > > > > In a terminal, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > curl https://binaries.cockroachdb.com/ccloud/ccloud_linux-amd64_.tar.gz | tar -xz && cp -i ccloud /usr/local/bin/ > > > ``` > > > > > [tab] Windows > > > > > > In a PowerShell window, enter the following command to download and extract the `ccloud` binary and add it to your `PATH`: > > > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_.zip -OutFile ccloud.zip; Expand-Archive -Force -Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination $env:appdata/ccloud; $Env:PATH += ";$env:appdata/ccloud"; # We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information. > > > ``` > > > > ### Run `ccloud quickstart` to create a new cluster, create a SQL user, and retrieve the connection string. > > > > The easiest way of getting started with CockroachDB Cloud is to use `ccloud quickstart`. The `ccloud quickstart` command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run `ccloud quickstart` and follow the instructions: > > > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > ccloud quickstart > > ``` > > > > The `ccloud quickstart` command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address. > > > > The `ccloud quickstart` command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option. > > > > Select **General connection string**, then copy the connection string displayed and save it in a secure location. The connection string is the line starting `postgresql://`. > > > > ``` > > ? How would you like to connect? General connection string > > Retrieving cluster info: succeeded > > Downloading cluster cert to /Users/maxroach/.postgresql/root.crt: succeeded > > postgresql://maxroach:ThisIsNotAGoodPassword@blue-dog-147.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=%2FUsers%2Fmaxroach%2F.postgresql%2Froot.crt > > ``` > [tab] Use a Local Cluster > > 1. If you haven't already, [download the CockroachDB binary](/docs/stable/install-cockroachdb-mac). > > 2. Run the [`cockroach start-single-node`](/docs/stable/cockroach-start-single-node) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start-single-node --advertise-addr 'localhost' --insecure > ``` > > This starts an insecure, single-node cluster. > > 3. Take note of the following connection information in the SQL shell welcome text: > > ``` > CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s) > build: CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11) > webui: http://localhost:8080 > sql: postgresql://root@localhost:26257?sslmode=disable > ``` > > You'll use the `sql` connection string to connect to the cluster later in this tutorial. > > > [!CAUTION] > > > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. ## Step 2. Get the code 1. Clone [the code's GitHub repository](https://github.com/cockroachlabs/example-app-typescript-typeorm): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ git clone git@github.com:cockroachlabs/example-app-typescript-typeorm.git ``` 2. Navigate to the repo directory and install the application dependencies: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd example-app-typescript-typeorm ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ npm install ``` ## Step 3. Configure your CockroachDB connection 1. Open the `datasource.ts` file, and comment out the `ssl: true`, `extra` and `options` configuration properties. 2. In the `datasource.ts` file, uncomment `ssl: { rejectUnauthorized: false }`. > [!CAUTION] > > Only use `ssl: { rejectUnauthorized: false }` in development, for insecure connections. The `DataSource` configuration should look similar to the following: ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export const AppDataSource = new DataSource({ type: "cockroachdb", url: process.env.DATABASE_URL, ssl: { rejectUnauthorized: false }, // For insecure connections only synchronize: true, logging: false, entities: ["src/entity/**/*.ts"], migrations: ["src/migration/**/*.ts"], subscribers: ["src/subscriber/**/*.ts"], }) ``` 1. Set the `DATABASE_URL` environment variable to the connection string provided in the `cockroach` welcome text: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" ``` 2. Set the `DATABASE_URL` environment variable to a CockroachDB connection string compatible with TypeORM. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL=" [tab] node.js > > The Node.js function code is located in the `examples-aws-lambda/node` directory and has the following structure: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ├── README.md > ├── deployment-package.zip ## Lambda deployment package > ├── index.js ## Lambda function source code > ├── package-lock.json ## Dependencies > └── package.json ## Dependencies > ``` > > The Lambda function uses the [node-postgres](https://node-postgres.com/) modules to connect to your cluster. > [tab] Python > > The Python function code is located in the `examples-aws-lambda/python` directory and has the following structure: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ├── README.md > ├── deployment-package.zip ## Lambda deployment package > ├── init_db.py ## Lambda function source code > ├── package ## Psycopg dependencies > ├── requirements.txt ## List of Python requirements > └── root.crt ## CA cert > ``` > > The Lambda function uses the [Psycopg2](https://www.psycopg.org/) PostgreSQL adapter to connect to your cluster. ## Step 3. (Optional) Create the deployment package Creating a deployment package to deploy the sample function is optional. The `examples-aws-lambda` repo includes deployment packages that are ready to deploy. 1. In the `node` directory, install the code dependencies: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cd node; npm install ``` 2. Compress the project files to a ZIP file in the parent directory for deployment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} zip -r ../my-deployment-package.zip . ``` 3. In the `python` directory, download and install the `psycopg2-binary` Python library: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cd python; python3 -m pip install \ --only-binary :all: \ --platform manylinux1_x86_64 \ --target ./my-package \ -r requirements.txt ``` > [!NOTE] > > To run on Amazon Linux distributions, `pscyopg2` dependencies must be compiled for Linux. 1. Compress the project files to a ZIP file in the parent directory for deployment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} zip -r ../my-deployment-package.zip my-deployment-package ./init_db.py ./root.crt ``` ## Step 4. Configure AWS 1. Configure the AWS CLI to authenticate with your AWS account: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} aws configure ``` Follow the prompts to authenticate as a user with administrator privileges. We do not recommend using the `root` user. 2. Create an execution role for the Lambda function and attach the `AWSLambdaBasicExecutionRole` policy to the role. The Lambda function needs this role to run. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} aws iam create-role \ --role-name lambda-ex \ --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} aws iam attach-role-policy \ --role-name lambda-ex \ --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole ``` ## Step 5. Deploy the function to AWS Lambda 1. In the deployment package directory, use the AWS CLI to create a Lambda function: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} aws lambda create-function \ --function-name init-crdb \ --region \ --zip-file fileb://deployment-package.zip \ --handler index.handler \ --runtime nodejs14.x \ --role arn:aws:iam:: \ --zip-file fileb://deployment-package.zip \ --handler init_db.lambda_handler \ --runtime python3.9 \ --role arn:aws:iam:: [!NOTE] > > To connect to a CockroachDB Standard cluster with Psycopg2, you must provide the client with a valid CA certificate. By default, Pscyopg2 searches for the certificate at `~/.postgresql/root.crt` and in the location point to by the environment variable `PGSSLROOTCERT`. 1. Invoke the function: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} aws lambda invoke \ --function-name init-crdb out \ --log-type Tail \ --query 'LogResult' \ --output text | base64 -d ``` ``` START RequestId: 12232b98-daac-4a1e-80e9-f2ecaa6497aa Version: $LATEST 2022-02-16T19:24:49.569Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Initializing table... 2022-02-16T19:24:49.596Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Hey! You successfully connected to your CockroachDB cluster. 2022-02-16T19:24:49.635Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Created new account with balance 320. 2022-02-16T19:24:49.655Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Created new account with balance 593. 2022-02-16T19:24:49.660Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Created new account with balance 277. 2022-02-16T19:24:49.675Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Created new account with balance 844. 2022-02-16T19:24:49.680Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Created new account with balance 257. 2022-02-16T19:24:49.680Z 12232b98-daac-4a1e-80e9-f2ecaa6497aa INFO Database initialized. END RequestId: 12232b98-daac-4a1e-80e9-f2ecaa6497aa REPORT RequestId: 12232b98-daac-4a1e-80e9-f2ecaa6497aa Duration: 644.49 ms Billed Duration: 645 ms Memory Size: 128 MB Max Memory Used: 63 MB Init Duration: 198.77 ms ``` ## See also * [Build a Simple Django App with CockroachDB](/docs/v26.4/build-a-python-app-with-cockroachdb-django) You might also be interested in the following pages: * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Connection Pooling](/docs/v26.4/connection-pooling) * [Data Replication](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) # Developer Basics Source: https://docs.cockroachlabs.com/docs/stable/developer-basics Before you start using CockroachDB, you should understand the following important mechanics of the database: * [How transactions work in CockroachDB](#how-transactions-work-in-cockroachdb), including [serializability](#serializability-and-transaction-contention) and [transaction retries](#transaction-retries) * [How applications interact with CockroachDB](#how-applications-interact-with-cockroachdb) Note that the sections that follow were written for the purposes of orienting application developers. For more detailed technical documentation on CockroachDB's architecture, see our [architecture documentation](/docs/v26.4/architecture/overview). ### How transactions work in CockroachDB CockroachDB is designed to make your data scalable and consistent. All stored records are replicated across a distributed deployment of database instances, and all database transactions committed in CockroachDB satisfy [ACID properties](https://en.wikipedia.org/wiki/ACID). To guarantee that database operations are [atomic](https://wikipedia.org/wiki/Atomicity_\(database_systems\)) (the "A" of the [ACID properties](https://en.wikipedia.org/wiki/ACID)), CockroachDB executes all statements in the context of an atomic [database transaction](https://wikipedia.org/wiki/Database_transaction). If a transaction succeeds, all data mutations are applied together simultaneously from the perspective of operations outside of the transaction. If any part of a transaction fails, the entire transaction is aborted, and the database is left unchanged. Managing transactions is an important part of CockroachDB application development. When creating your application's persistence layer, you must understand how CockroachDB interacts with your application framework's transaction management system. You should also have some knowledge of CockroachDB's [transaction syntax](/docs/v26.4/transactions#syntax). We go into more detail about transaction management in [Manage Transactions](/docs/v26.4/transactions). #### Serializability and transaction contention By default, CockroachDB uses [`SERIALIZABLE`](/docs/v26.4/demo-serializable) transaction [isolation](https://wikipedia.org/wiki/Isolation_\(database_systems\)) (the "I" of ACID semantics). If transactions are executed concurrently, the final state of the database will appear as if the transactions were executed serially. `SERIALIZABLE` isolation, the strictest level of isolation, provides the highest level of data consistency and protects against concurrency anomalies. To guarantee data consistency, CockroachDB [locks](/docs/v26.4/architecture/transaction-layer#concurrency-control) the data targeted by an open transaction. If a separate transaction attempts to modify data that are locked by an open transaction, the newest transaction will not succeed, as committing it could result in incorrect data. This scenario is called *transaction contention*, and should be avoided when possible. For a more detailed explanation of transaction contention, and tips on how to avoid it, see [Transaction contention](/docs/v26.4/performance-best-practices-overview#transaction-contention). #### Transaction retries In some cases, [transaction contention](/docs/v26.4/performance-best-practices-overview#transaction-contention) is unavoidable. If a transaction fails due to contention, CockroachDB will automatically retry the transaction. If the transaction is `SERIALIZABLE` and cannot automatically be retried without allowing [serialization](/docs/v26.4/demo-serializable) anomalies, CockroachDB will return a [transaction retry error](/docs/v26.4/transaction-retry-error-reference) to the client. Most [official CockroachDB client libraries](/docs/v26.4/install-client-drivers) include a transaction-retrying wrapper function to make writing your persistence layer easier. If your framework's client library does not include a retry wrapper, you will need to write transaction retry logic in your application. We go into more detail about transaction retries later in the guide, in [Retry Transactions](/docs/v26.4/advanced-client-side-transaction-retries). #### Read Committed isolation CockroachDB can be configured to execute transactions at [`READ COMMITTED`](/docs/v26.4/read-committed) instead of `SERIALIZABLE` isolation. `READ COMMITTED` permits some concurrency anomalies in exchange for minimizing transaction aborts and removing the need for client-side retries. Depending on your workload requirements, this may be desirable. For more information, see [Read Committed Transactions](/docs/v26.4/read-committed). ### How applications interact with CockroachDB CockroachDB supports the PostgreSQL wire protocol, and CockroachDB supports [most PostgreSQL syntax and features](/docs/v26.4/postgresql-compatibility), making most PostgreSQL client libraries compatible with CockroachDB. Cockroach Labs also maintains official CockroachDB adapters for some of the most popular PostgreSQL drivers and ORMs. Using an official CockroachDB adapter can help simplify transaction management and performance optimization in your application. If an official CockroachDB adapter does not yet exist for your application's data framework, we recommend just using the PostgreSQL client library that works for your application. A growing number of popular third-party database tools offer full support for CockroachDB. Because CockroachDB uses the PostgreSQL wire protocol and supports PostgreSQL syntax, most PostgreSQL-compatible third-party tools are also compatible with CockroachDB. For a list of libraries and tools that we have tested against CockroachDB, see [Third-party Database Tools](/docs/v26.4/third-party-database-tools). # Install a FIPS-ready CockroachDB Runtime Source: https://docs.cockroachlabs.com/docs/stable/fips > [!NOTE] > > **What "FIPS support" means** > > When CockroachDB documentation refers to "FIPS support" or "FIPS-ready" deployments, this means CockroachDB can be configured to use FIPS 140-3-approved cryptographic algorithms and operate in accordance with a FIPS 140-3 cryptographic module's Security Policy. It does not mean that CockroachDB itself is FIPS 140-3 validated. > > CockroachDB uses the frozen Go Cryptographic Module v1.0.0, which is FIPS 140-3 validated under [CMVP Certificate #5247](https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/5247). ## Overview of FIPS-ready CockroachDB [Federal Information Processing Standards (FIPS) 140-3](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-3.pdf) is a U.S. government standard that specifies security requirements for cryptographic modules. FIPS 140-3 provides measurable security guidelines for protecting sensitive but unclassified information. The standard is applicable to all federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems. U.S. and Canadian governments, as well as organizations working with them, may be subject to FIPS 140-3 requirements. The Cryptographic Module Validation Program (CMVP) validates cryptographic modules to FIPS 140-3 and other cryptography-based standards. When a cryptographic module or library has a FIPS 140-3 certificate, it has been tested and formally validated under the CMVP as meeting the requirements for FIPS 140-3. FIPS-ready CockroachDB binaries and Docker images are available for CockroachDB v23.1.0 and later. FIPS-ready CockroachDB runtimes run on Intel 64-bit Linux systems. Starting with v26.1, FIPS-ready CockroachDB binaries are built using Go's native FIPS 140-3 support. The cryptographic operations are performed by Go's built-in cryptographic modules, which are independent of the host operating system's libraries. This represents a significant architectural change from previous versions (v25.4 and earlier), which used Red Hat's golang-fips toolchain with OpenSSL. > [!NOTE] > > **Migration from FIPS 140-2 to FIPS 140-3** > > Previous versions of CockroachDB (v25.4 and earlier) supported FIPS 140-2. Starting with v26.1, CockroachDB uses a cryptographic module designed for FIPS 140-3 support. Starting with v26.2, CockroachDB uses `GOFIPS140=v1.0.0`, the frozen module version that is FIPS 140-3 validated under [CMVP Certificate #5247](https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/5247). > > FIPS 140-2 will transition to historical status on September 22, 2026, per [NIST's FIPS 140-3 Transition Effort](https://csrc.nist.gov/Projects/fips-140-3-transition-effort). For details about cryptographic algorithms and key lengths used by CockroachDB, refer to [Details About Cryptographic Algorithms](#details-about-cryptographic-algorithms). ### FIPS-ready features When you use a FIPS-ready CockroachDB runtime, Cockroach Labs has verified that cryptographic operations in the following contexts meet the requirements of FIPS 140-3: * [Encryption At Rest](/docs/v26.4/security-reference/encryption) * [Encrypted Backups](/docs/v26.4/take-and-restore-encrypted-backups) * [Change Data Capture to Kafka over TLS](/docs/v26.4/create-changefeed#query-parameters) * [Certificate-based Node-to-Node and Client-to-Node Authentication](/docs/v26.4/authentication) * [SASL SCRAM-SHA-256 Password Authentication](/docs/v26.4/security-reference/scram-authentication) * [SQL Cryptographic Built-in Functions](/docs/v26.4/functions-and-operators#cryptographic-functions) > [!CAUTION] > > When running a FIPS-ready runtime, Cockroach Labs recommends that you avoid using cryptographic operations that are not supported by FIPS 140-3. For example, generating an MD5 hash is not compatible with FIPS 140-3, because MD5 is not a FIPS-validated algorithm. Use algorithms and functions that do not comply with the standard at your own risk. This page shows how to install and configure a FIPS-ready CockroachDB runtime using Go's native FIPS 140-3 support. ### Performance considerations When comparing performance of the same workload in a FIPS-ready CockroachDB runtime to a standard CockroachDB runtime, some performance difference may be observed. The amount of performance impact depends upon the workload, cluster configuration, query load, and other factors. ### Upgrading to a FIPS-ready CockroachDB runtime Upgrading an existing CockroachDB cluster's binaries in-place to be FIPS-ready is not supported. ## Operating system requirements FIPS-ready CockroachDB uses Go's native cryptographic module, which is independent of the host operating system's libraries. The FIPS-ready binary can run on any Intel 64-bit Linux system. The FIPS-ready CockroachDB Docker images are based on [Red Hat's Universal Base Image 10](https://catalog.redhat.com/software/containers/ubi10/ubi-minimal/). To [use the FIPS-ready CockroachDB Docker image](#use-the-fips-ready-cockroachdb-docker-image), skip directly to that section of this page. ### Extend Red Hat's Universal Base Image 10 Docker image If you do not want to use the FIPS-ready CockroachDB Docker image directly, you can create a custom Docker image based on [Red Hat's Universal Base Image 10](https://catalog.redhat.com/software/containers/ubi10/ubi-minimal/): * The FIPS-ready binary includes the FIPS 140-3 Go Cryptographic Module and does not require additional system libraries to be installed. ## Download FIPS-ready runtimes FIPS-ready runtimes are not yet available for CockroachDB v26.4. Download links will be added when v26.4.0 becomes available for self-hosted deployments. ## Install the FIPS-ready CockroachDB runtime When FIPS-ready CockroachDB v26.4 binaries become available, install them in the same way as standard binaries. Refer to [Install CockroachDB on Linux](/docs/v26.4/install-cockroachdb-linux). > [!NOTE] > > **Upgrade from v25.4 or v26.1 FIPS to v26.2 or later** > > CockroachDB v26.1 and later use Go's native FIPS cryptographic module, a significant architectural change from the OpenSSL-based approach used in v25.4 and earlier. FIPS support was Preview in v26.1, so deployments using FIPS on v25.4 or v26.1 should upgrade to v26.2 or a later version. > > Upgrading an existing CockroachDB cluster's binary in-place from non-FIPS to FIPS is not supported. Instead, you can [restore your cluster](/docs/v26.4/restore#full-cluster) to a new FIPS-ready cluster. ### Verify that CockroachDB is FIPS-ready To verify that the CockroachDB binary is FIPS-ready, use the `cockroach version` command and check for the `FIPS enabled` field: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach version | grep -i fips ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} FIPS enabled: true ``` This indicates that CockroachDB was built with Go's native FIPS 140-3 support. > [!NOTE] > > **Change from previous versions:** In v25.4 and earlier, FIPS-ready binaries showed `fips` appended to the Go version (e.g., `go1.19.5fips`). Starting with v26.1, FIPS status is indicated by the `FIPS enabled: true` field. ## Use the FIPS-ready CockroachDB Docker image FIPS-ready CockroachDB Docker images are not yet available for CockroachDB v26.4. Image tags and usage instructions will be added when v26.4.0 becomes available for self-hosted deployments. ## Details about cryptographic algorithms This section provides more information about the cryptographic algorithms and key lengths used by FIPS-ready CockroachDB. ### Authentication #### Inter-node and node identity **Algorithm**: [TLS 1.3 (RFC 8446)](https://www.rfc-editor.org/rfc/rfc8446). Refer to [Using Digital Certificates with CockroachDB](/docs/v26.4/authentication#using-digital-certificates-with-cockroachdb). #### Client identity ##### Password authentication **Algorithm**: `bcrypt` or `scram-sha-256`. Refer to [SASL/SCRAM-SHA-256 Secure Password-based Authentication](/docs/v26.4/security-reference/scram-authentication). ##### Client certificates **Algorithm**: [TLS 1.3 (RFC 8446)](https://www.rfc-editor.org/rfc/rfc8446). Refer to [Using Digital Certificates with CockroachDB](/docs/v26.4/authentication#using-digital-certificates-with-cockroachdb). ##### GSSAPI / Kerberos Not supported for FIPS-ready deployments. ##### SASL / SCRAM password authentication **Algorithm**: `scram-sha-256`. Refer to [SASL/SCRAM-SHA-256 Secure Password-based Authentication](/docs/v26.4/security-reference/scram-authentication). ##### JSON Web Tokens (JWTs) **Algorithms**: Specified by the [`server.jwt_authentication.jwks` cluster setting](/docs/v26.4/sso-sql#cluster-settings). Refer to [Cluster Single Sign-on (SSO) using a JSON web token (JWT)](/docs/v26.4/sso-sql). ##### DB Console authentication via OIDC **Algorithm**: Specified by the identity provider (IdP) as part of the OIDC handshake process. Refer to [Single Sign-on (SSO) for DB Console](/docs/v26.4/sso-db-console). ##### HTTP API access via login tokens **Algorithm**: `sha256` ([RFC 6234](https://datatracker.ietf.org/doc/html/rfc6234)). ### Encryption #### In flight **Algorithm**: [TLS 1.3 (RFC 8446)](https://www.rfc-editor.org/rfc/rfc8446). **Key sizes**: Depends upon the cipher suite in use: * TLS 1.2: * `tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256` * `tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` * `tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` * `tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` * If the `COCKROACH_TLS_ENABLE_OLD_CIPHER_SUITES` environment variable is set: * `tls.TLS_RSA_WITH_AES_128_GCM_SHA256` * `tls.TLS_RSA_WITH_AES_256_GCM_SHA384` * TLS 1.3: * `TLS_AES_128_GCM_SHA256` * `TLS_AES_256_GCM_SHA384` #### At rest ##### Customer-managed backups ##### AWS Default encryption provided by the [AWS Encryption SDK](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html). ##### GCP Default encryption provided by [Google Cloud](https://cloud.google.com/docs/security/encryption/default-encryption). ##### Data Encryption at Rest (EAR) **Algorithm**: Advanced Encryption Standard (AES) encryption, in counter (CTR) mode. **Key sizes**: The store key is specified by the user, and can be of length 16, 24, or 32 bytes (corresponding to AES-128, AES-192, or AES-256). Data keys are the same length as the store key. ## See also * [Install CockroachDB](/docs/v26.4/install-cockroachdb-linux) * [Releases](/docs/releases/index) # Build a GraphQL Application Using Hasura Source: https://docs.cockroachlabs.com/docs/stable/hasura-getting-started This tutorial shows you how to create a GraphQL application using [Hasura Cloud](https://cloud.hasura.io) and CockroachDB Standard. The Hasura GraphQL Engine creates [GraphQL](https://graphql.org/) schemas and resolvers based on the tables and views in your CockroachDB cluster, allowing you to submit GraphQL queries to access and manipulate your data. Hasura GraphQL Engine v2.16 and later supports CockroachDB v22.2 and later. ## Overview This tutorial will show you how to configure a Hasura project with a CockroachDB data source, allow connections to your CockroachDB cluster from Hasura Cloud, and create a table that is then used with Hasura GraphQL Engine to retrieve and modify data. ## Before you begin Before you start this tutorial, you need: * An existing [CockroachDB Cloud](/docs/cockroachcloud/quickstart) cluster, running CockroachDB v22.2 or later. * A [Hasura Cloud account](https://hasura.io/docs/latest/getting-started/getting-started-cloud/). ## Create a new project in Hasura Cloud 1. In the Hasura Cloud console, select **Projects**, then click **New Project**. 2. In the **Create Project** panel select the cloud infrastructure provider and region. The cloud infrastructure provider and region should match your cluster. For example, if you created a CockroachDB Standard cluster in GCP's `us-east1` region, choose a GCP region closest to `us-east1`. 3. Click **Create Free Project**. ### Add environment variables to your project You will store your cluster root certificate and connection string in your Hasura project's environment variables. Storing this connection information in environment variables is considered a best practice. Create a `SSL_ROOT_CERT` environment variable for your cluster's CA cert. 1. Select **Env vars** in your project settings, and click **New Env Var**. 2. Under **Key** type `SSL_ROOT_CERT`, then press **Enter**. 3. Copy the contents of your cluster's CA certificate file you downloaded earlier. For example, on Mac you can copy the contents of the CA certificate in a terminal using `pbcopy`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} pbcopy < $HOME/.postgresql/root.crt ``` 4. Paste the contents of the CA certificate file under **Value**. 5. Click **Add**. 6. Select **Env vars** in your project settings, and click **New Env Var**. 7. Under **Key** type `SSL_ROOT_CERT`, then press **Enter**. 8. Copy the contents of your CockroachDB Standard cluster's CA certificate file you downloaded earlier. For example, on Mac you can copy the contents of the CA certificate in a terminal using `pbcopy`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} pbcopy < $HOME/Library/CockroachCloud/certs/fake-puppy-ca.crt ``` 9. Paste the contents of the CA certificate file under **Value**. ![Adding the SSL_ROOT_CERT environment variable to the Hasura project](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/hasura-ca-cert.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=65944c4f8f065b4defabf39e3e0fc963) 10. Click **Add**. Create a `CRDB_URL` environment variable to store the connection string. 1. Click **New Env Var**. 2. Under **Key** type `CRDB_URL`, then press **Enter**. 3. Paste the connection string for your cluster you copied earlier. Add your SQL user password if necessary to the connection string. 4. Remove the `sslmode` and `sslrootcert` query parameters from the end of the connection string. You will add the SSL settings later. For example, if your connection string in the CockroachDB Cloud console is: ``` postgresql://maxroach:NotAGoodPassword@fake-puppy-595.g95.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full ``` You would modify the connection string to: ``` postgresql://maxroach:NotAGoodPassword@fake-puppy-595.g95.cockroachlabs.cloud:26257/defaultdb ``` 5. Click **Add**. ### Create a Data Source in Hasura Cloud 1. In the overview page in Hasura Cloud, select **Projects**, find the project you created earlier, and click **Launch Console**. 2. Click **Data** in the console header to open the **Data Manager**. 3. Click **Connect Database**. 4. In the **Connect Existing Database** tab configure the connection to your cluster. 1. Under **Database Display Name** type a name for your connection. Your cluster name is a good option. For example, `fake-puppy`. 2. Set **Data Source Driver** to **CockroachDB**. 3. Select **Environment Variable**, then enter `CRDB_URL` in the **Environment Variable** input box. ![Adding the connection string to the Hasura Data Manager](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/hasura-data-source.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=944d7ee57091aa0f959adb152cfeb0b3) 5. Expand **Connection Settings**, then expand **SSL Certificates Settings** and set **SSL Mode** to `verify-full`. 6. Enter `SSL_ROOT_CERT` under **SSL Root Certificate**, the environment variable you configured earlier. 7. Click **Connect Database**. ## Add the Hasura Cloud network to your cluster allowlist Your CockroachDB Standard cluster needs to be configured to [allow incoming client connections](/docs/cockroachcloud/network-authorization#ip-allowlisting) from Hasura Cloud. 1. In the Hasura Cloud overview page select **Projects**, then click the **Config** icon for your project. ![Click the project Config icon](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/hasura-project-config.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=aca02657f15f1be887809e4d7d54458f) 2. In the **General** section, copy the IP address listed under **Hasura Cloud IP**. 3. In the CockroachDB Cloud console select your cluster, click **Networking**, then **Add Network**. 4. In the **Add Network** dialog, set **Network name** to `Hasura Cloud`. 5. Under **Network**, select **New Network**. Paste the IP address of your Hasura Cloud instance you copied earlier. 6. Check **CockroachDB Client to access the databases**, then click **Apply**. ## Create a table in your CockroachDB cluster 1. Connect to your cluster using the SQL client. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --url "{connection string}" ``` Where `{connection string}` is the connection string for your cluster you copied earlier. 2. In the SQL client, create an `accounts` table. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE TABLE IF NOT EXISTS accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), balance INT8 ); ``` 3. Insert some data into the `accounts` table. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} UPSERT INTO accounts (balance) VALUES (1000), (250); ``` This will create two accounts, one with $1000 and another with $250. ## Track the `accounts` table in the Hasura Cloud Data Manager 1. In the Hasura Cloud Data Manager click `public` under your connection name. 2. Click the **Track All** button. 3. Click **Yes** when prompted to expose the table to the GraphQL API. ### Create a GraphQL query in the Hasura Cloud API Explorer In the Hasura Cloud Explorer, you will see the `accounts` table. You can expand `accounts` to construct a GraphQL query against the `accounts` table. For example, to create a query that finds all accounts with balances greater than or equal to \$500: 1. Enter `GetLargeAccounts` as the query name in the Explorer. 2. Expand `accounts` in the Explorer. 3. Check `balance` and `id`, then expand `where`, then `balance`. 4. Check `_gte` to create a "greater than or equal to" where clause for `balance`, then enter `500`. This creates the following GraphQL query: ```graphql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} query GetLargeAccounts { accounts(where: {balance: {_gte: "500"}}) { balance id } } ``` Click the **Execute Query** button to run the `GetLargeAccounts` GraphQL query. The returned data should look like the following: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "data": { "accounts": [ { "balance": 1000, "id": "2ed41abf-e831-42df-aff4-f88a6f2b0afc" } ] } } ``` ![Executing the GraphQL query in the Hasura Cloud API Explorer](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/hasura-execute-query.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=7ae8dc20611200b3d1ec42bd571f15d0) ## Next steps Now that you have connected your cluster to Hasura GraphQL Engine, you can use the Explorer to create GraphQL queries to access and modify data in your cluster's tables. You can then use these queries in your application. For example, you can create [Hasura Actions](https://hasura.io/docs/latest/actions/index/?utm_source=cockroachdb) that use these queries. See the [Hasura documentation](https://hasura.io/docs/latest/index/?utm_source=cockroachdb) for detailed information on integrating and deploying Hasura in your applications. # CockroachDB Docs Source: https://docs.cockroachlabs.com/docs/stable/index CockroachDB is the SQL database for building global, scalable cloud services that survive disasters. ![icon browser](https://mintcdn.com/cockroachlabs/bALSwIJ7kkDMfVP4/images/icon-in-browser.svg?fit=max\&auto=format\&n=bALSwIJ7kkDMfVP4\&q=85\&s=d6aa168b7f7520212efddf111c50eecb) ### [Start a Cloud cluster](/docs/cockroachcloud/quickstart) ![download](https://mintcdn.com/cockroachlabs/DKqs6KegExsX2OUa/images/icon-download-binary.svg?fit=max\&auto=format\&n=DKqs6KegExsX2OUa\&q=85\&s=ce0a61366754a43130dcfea1ed379247) ### [Download the CockroachDB binary](/docs/releases) ![MCP server](https://mintcdn.com/cockroachlabs/DKqs6KegExsX2OUa/images/icon-mcp-server.svg?fit=max\&auto=format\&n=DKqs6KegExsX2OUa\&q=85\&s=7d508e6b25294d6f3021d112d7c5257f) ### [Use the Docs MCP server](/docs/v26.4/docs-mcp-integration) ## Recommended articles ### Get Started

  • [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac)
  • [Start a Local Cluster](/docs/v26.4/secure-a-cluster)
  • [Connect to the Database](/docs/v26.4/connect-to-the-database)
  • [Learn CockroachDB SQL](/docs/v26.4/learn-cockroachdb-sql)
  • [Explore Capabilities](/docs/v26.4/demo-cockroachdb-resilience)
### CockroachDB and AI
  • [CockroachDB and AI Overview](/docs/v26.4/cockroachdb-and-ai)
  • [Vector Indexes](/docs/v26.4/vector-indexes)
  • [Agent Skills](/docs/v26.4/agent-skills)
  • [Docs MCP Server](/docs/v26.4/docs-mcp-integration)
### Deploy
  • [Production Checklist](/docs/v26.4/recommended-production-settings)
  • [CockroachDB Cloud Deployment](/docs/cockroachcloud/create-your-cluster)
  • [Kubernetes Overview](/docs/v26.4/cockroachdb-operator-overview)
  • [Multi-Region Capabilities](/docs/v26.4/multiregion-overview)
  • [Cluster Maintenance](/docs/v26.4/upgrade-cockroach-version)
### Migrate
  • [Migration Overview](/docs/molt/migration-overview)
  • [Migrate from PostgreSQL](/docs/molt/migrate-to-cockroachdb)
  • [Migrate from MySQL](/docs/molt/migrate-to-cockroachdb?filters=mysql)
  • [Migrate from Oracle](/docs/molt/migrate-to-cockroachdb)
  • [MOLT Fetch](/docs/molt/molt-fetch)
### Security
  • [Security Overview](/docs/v26.4/security-reference/security-overview)
  • [Authentication](/docs/v26.4/authentication)
  • [Authorization](/docs/v26.4/authorization)
  • [Encryption](/docs/v26.4/encryption)
### Reference
  • [Architecture](/docs/v26.4/architecture/overview)
  • [SQL](/docs/v26.4/sql-statements)
  • [CLI](/docs/v26.4/cockroach-commands)
  • [DB Console](/docs/v26.4/ui-overview)
  • [Third-Party Tools](/docs/v26.4/third-party-database-tools)
Learning Resources Cockroach University Free online learning platform covering distributed databases, cloud-native applications, general purpose SQL databases & much more! [Start free course ![icon arrow right](https://mintcdn.com/cockroachlabs/bALSwIJ7kkDMfVP4/images/icon-arrow-right-ice-temple.svg?fit=max\&auto=format\&n=bALSwIJ7kkDMfVP4\&q=85\&s=bea0638070071ce5081406f3517ce376)](https://www.cockroachlabs.com/cockroach-university/) Report ## [The State of Resilience 2025](https://www.cockroachlabs.com/guides/the-state-of-resilience-2025/) Cockroach LabsOctober 29, 2025 # Install CockroachDB on Linux Source: https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-linux > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the [Cloud Quickstart](/docs/cockroachcloud/quickstart). > **This page refers to CockroachDB v26.4.** For the latest supported release, refer to the [Release Support Policy](/docs/releases/release-support-policy). > Use one of the options below to install CockroachDB. To upgrade an existing cluster, refer to [Upgrade to v26.4](/docs/v26.4/upgrade-cockroach-version). > > * To install a FIPS-compliant CockroachDB binary, refer to [Install a FIPS-compliant build of CockroachDB](/docs/v26.4/fips) instead of this page. > * For limitations of CockroachDB on ARM, refer to [ARM limitations](#arm). > * For limitations of CockroachDB on a NUMA architecture, refer to [NUMA limitations](#numa). ## Download the binary The CockroachDB binary for Linux requires `glibc`, `libncurses`, and `tzdata`, which are found by default on nearly all Linux distributions. 1. Visit [Releases](/docs/releases/index) to download the CockroachDB archive for the architecture of your Linux host. The archive contains the `cockroach` binary and the supporting libraries that are used to provide [spatial features](/docs/v26.4/spatial-data-overview). Follow the steps shown below to install the `cockroach` binary into your `PATH` so you can execute [cockroach commands](/docs/v26.4/cockroach-commands) from any shell. 1. Download the binary you want from the [Releases](/docs/releases/index) page. In the following commands, replace `VERSION` with the version of CockroachDB you are installing (e.g., v26.4), and replace `ARCHITECTURE` with `linux-amd64` for Intel, or with `linux-arm64` for ARM. 2. Extract the archive: ``` tar-xz cockroach-VERSION.linux-ARCHITECTURE.tgz ``` 3. Copy the `cockroach` binary into your `PATH`: ``` cp -i cockroach-VERSION.linux-ARCHITECTURE/cockroach /usr/local/bin/ ``` If you plan to use CockroachDB's [spatial features](/docs/v26.4/spatial-data-overview), you must complete the following steps. Otherwise, your installation is now complete. 2. CockroachDB uses custom-built versions of the [GEOS](/docs/v26.4/architecture/glossary#geos) libraries. Copy these libraries to one of the locations where CockroachDB expects to find them. By default, CockroachDB looks for external libraries in `/usr/local/lib/cockroach` or a `lib` subdirectory of the CockroachDB binary's current directory. If you place these libraries in another location, you must pass the location in the [`--spatial-libs` flag to `cockroach start`](/docs/v26.4/cockroach-start#flags-spatial-libs). The instructions below assume the `/usr/local/lib/cockroach` location. 1. Create the directory where the external libraries will be stored: ``` mkdir -p /usr/local/lib/cockroach ``` 2. Copy the library files to the directory. In the following commands, replace `VERSION` with the version of CockroachDB you are installing, and replace `ARCHITECTURE` with `linux-amd64` for Intel, or with `linux-arm64` for ARM. ``` cp -i cockroach-VERSION.linux-ARCHITECTURE/lib/libgeos.so /usr/local/lib/cockroach/ ``` ``` cp -i cockroach-VERSION.linux-ARCHITECTURE/lib/libgeos_c.so /usr/local/lib/cockroach/ ``` If you get a permissions error, prefix the command with `sudo`. 3. Verify that CockroachDB can execute spatial queries. 1. Make sure the `cockroach` binary you just installed is the one that runs when you type `cockroach` in your shell: ``` which cockroach ``` ``` /usr/local/bin/cockroach ``` 2. Start a temporary, in-memory cluster using [`cockroach demo`](/docs/v26.4/cockroach-demo): ``` cockroach demo ``` * In the demo cluster's interactive SQL shell, run the following command to test that the spatial libraries have loaded properly: ``` > SELECT ST_IsValid(ST_MakePoint(1,2)); ``` You should see the following output: ``` st_isvalid -------------- true (1 row) ``` If your `cockroach` binary is not properly accessing the dynamically linked C libraries in `/usr/local/lib/cockroach`, it will output an error message like the one below. ``` ERROR: st_isvalid(): geos: error during GEOS init: geos: cannot load GEOS from dir "/usr/local/lib/cockroach": failed to execute dlopen Failed running "sql" ``` * Keep up-to-date with CockroachDB releases and best practices: ## Use Kubernetes To orchestrate CockroachDB using [Kubernetes](https://kubernetes.io/), use the official [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview#cockroachdb-operator). You can evaluate a CockroachDB Kubernetes deployment on a local machine with [minikube](https://minikube.sigs.k8s.io/docs/start/). ## Use Docker > [!CAUTION] > > Running a stateful application like CockroachDB in Docker is more complex and error-prone than most uses of Docker. Unless you are very experienced with Docker, we recommend starting with a different installation and deployment method. > CockroachDB's Docker images are [multi-platform images](https://docs.docker.com/build/building/multi-platform/) that contain binaries for both Intel and ARM. Multi-platform images do not take up additional space on your Docker host. > Experimental images are not qualified for production use and not eligible for support or uptime SLA commitments. > > 1. Install a container runtime, such as [Docker Desktop](https://docs.docker.com/desktop/). > 2. Verify that the runtime service is installed correctly and running in the background. Refer to the runtime's documentation. For Docker, start a terminal and run `docker version`. If you get an error, verify your installation and try again. > 3. Visit [Docker Hub](https://hub.docker.com/r/cockroachdb/cockroach) and decide which image tag to pull. Releases are rolled out gradually. Docker images for a new release are published when other binary artifacts are published. The following tag formats are commonly used, although other tags are available. | Tag | Example | Description | | - | - | - | | An exact patch | \`\` | Pins a cluster to an exact patch. The cluster is upgraded to a newer patch or major version only when you pull a newer tag. | | Latest patch within a major version | `latest-v26.4` | Automatically updates a cluster to the latest patch of the version you specify. This tag is recommended in production, because it keeps your cluster updated within a major version but does not automatically upgrade your cluster to a new major version. | | `latest` | The latest patch within the latest major version. This is the default if you do not specify a tag. It updates your cluster automatically to each new patch and major version, and is not recommended in production. | | Copy the tag you want to pull. 1. Pull the image. Replace `{TAG}` with the tag from the previous step. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} docker pull cockroachdb/cockroach:{TAG} ``` 1. Start a cluster by starting the container on each node using `docker start`. The default command is `cockroach start`. Pass your desired flags as the final argument. For details, refer to [Deploy a local container in Docker](/docs/v26.4/start-a-local-cluster-in-docker). For CockroachDB v22.2.beta-5 and above, Docker images are [multi-platform images](https://docs.docker.com/build/building/multi-platform/) that contain binaries for both Intel and ARM. Multi-platform images do not take up additional space on your Docker host. Docker images for previous releases contain Intel binaries only. Intel binaries can run on ARM systems, but with a significant reduction in performance. CockroachDB on ARM is in **[Limited Access](/docs/releases/cockroachdb-feature-availability#feature-availability-phases)** in v22.2.13, and is **experimental** in all other versions. Experimental images are not qualified for production use and not eligible for support or uptime SLA commitments. 1. Install [Docker for Linux](https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/). Please carefully check that you meet all prerequisites. 2. Confirm that the Docker daemon is running in the background: ``` $ docker version ``` If you do not see the server listed, start the **Docker** daemon. 3. Pull the image for the release of CockroachDB from [Docker Hub](https://hub.docker.com/r//): ``` $ sudo docker pull : ``` 4. Keep up-to-date with CockroachDB releases and best practices: ## Build from source See the [public wiki](https://wiki.crdb.io/wiki/spaces/CRDB/pages/181338446/Getting+and+building+CockroachDB+from+source) for guidance. When building on the ARM architecture, refer to [Limitations](#limitations). ## Limitations ### ARM CockroachDB runtimes built for the ARM architecture have the following limitations: * Floating point operations may yield different results on ARM than on Intel, particularly [Fused Multiply Add (FMA) intrinsics](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation#Fused_multiply.E2.80.93add). Validate workloads that rely on floating point operations or FMA instrincs before migrating those workloads to ARM in production. * When [building from source](#install-source) on ARM, it is not currently possible to disable FMA intrinsics in Go. To track the status of this feature request, refer to [GoLang issue #36971](https://github.com/golang/go/issues/36971). * In production, Cockroach Labs recommends that all cluster nodes have identical CockroachDB versions, CPU architecture, hardware, and software. * A mix of Intel and ARM nodes is supported as a temporary transitional state during the migration only. Cockroach Labs recommends that you test and validate your workload ahead of the migration to ensure that the workload and your application work as expected in a cluster with both Intel and ARM nodes, especially with respect to floating-point arithmetic. ### NUMA In a [NUMA (non-uniform memory access) architecture](https://en.wikipedia.org/wiki/Non-uniform_memory_access), the system’s memory is physically distributed across multiple memory banks or "nodes", and each node is assigned to a processor. A processor can access its local memory much faster than non-local memory. This non-uniform memory access can lead to performance differences depending on data location. CockroachDB is written in Go, which has no process-level support for NUMA scheduling or pinning. Instead, you must manage NUMA at the operating system level. To run multiple CockroachDB clusters on a NUMA architecture: * Assign no more than 64 cores to the node for each instance. Refer to the documentation for [`numactl --membind`](https://man7.org/linux/man-pages/man8/numactl.8.html). * Ensure that your orchestration framework, process manager, or startup scripts start each CockroachDB in a separate NUMA node. * If multiple CockroachDB nodes for the same CockroachDB cluster run on the same physical host, ensure that they are in the same [`--locality`](/docs/v26.4/architecture/replication-layer#intra-locality) to ensure that data is distributed across different physical hosts. * Ensure that each CockroachDB node writes to a unique set of storage volumes (block devices). ## What's next? * If you're just getting started with CockroachDB: * [Create a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?experience=enterprise) where you can [generate and manage licenses](/docs/v26.4/licensing-faqs) for CockroachDB installations * [Start a cluster locally](/docs/v26.4/start-a-local-cluster) and talk to it via the built-in SQL client * [Learn more about CockroachDB SQL](/docs/v26.4/learn-cockroachdb-sql) * [Explore CockroachDB features](/docs/v26.4/demo-replication-and-rebalancing) like automatic replication, rebalancing, and fault tolerance * If you're ready to run CockroachDB in production: * Review the [Production Checklist](/docs/v26.4/recommended-production-settings) * [Deploy CockroachDB manually](/docs/v26.4/manual-deployment) or [use an orchestration system like Kubernetes](/docs/v26.4/kubernetes-overview) # Install CockroachDB on Mac Source: https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-mac > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the [Cloud Quickstart](/docs/cockroachcloud/quickstart). > **This page refers to CockroachDB v26.4.** For the latest supported release, refer to the [Release Support Policy](/docs/releases/release-support-policy). For CockroachDB v22.2.x and above, Homebrew installs binaries for your system architecture, either Intel or ARM ([Apple Silicon](https://support.apple.com/HT211814)). For previous releases, Homebrew installs Intel binaries. Intel binaries can run on ARM systems, but with a significant reduction in performance. CockroachDB on ARM for macOS is **experimental** and is not yet qualified for production use and not eligible for support or uptime SLA commitments. For CockroachDB v22.2.x and above, download the binaries for your system architecture, either Intel or ARM ([Apple Silicon](https://support.apple.com/en-us/HT211814)). For previous releases, download Intel binaries. Intel binaries can run on ARM systems, but with a significant reduction in performance. CockroachDB on ARM for macOS is **experimental** and is not yet qualified for production use and not eligible for support or uptime SLA commitments. > [!NOTE] > > CockroachDB on macOS is experimental and not suitable for production deployments. > Use one of the options below to install CockroachDB. To upgrade an existing cluster, refer to [Upgrade to v26.4](/docs/v26.4/upgrade-cockroach-version). For limitations specific to geospatial features, refer to [Limitations](#limitations). ## Use Homebrew 1. [Install Homebrew](http://brew.sh/). 2. Instruct Homebrew to install CockroachDB: ``` $ brew install cockroachdb/tap/cockroach ``` 3. Keep up-to-date with CockroachDB releases and best practices: > [!TIP] > > If you previously installed CockroachDB via Homebrew, you can [upgrade](/docs/v26.4/upgrade-cockroach-version) the CockroachDB binary to the next major version or to a patch version using HomeBrew. After updating the binary on each node, restart the `cockroach` process on the node. When upgrading to a new major version, you must complete additional steps to [finalize](/docs/v26.4/upgrade-cockroach-version#finalize-a-major-version-upgrade-manually) the upgrade. If you need to upgrade through multiple major versions, you must complete each major-version upgrade separately, including finalizing the upgrade, before beginning the next one. > Before starting the upgrade, review the [release notes](/docs/releases/v26.4), including temporary limitations during the upgrade. > To upgrade CockroachDB via HomeBrew: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > brew update > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > brew update > brew upgrade cockroach > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > xattr -d com.apple.quarantine lib/libgeos\* > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > st_isvalid > -------------- > true > (1 row) > ``` ## Download the binary 1. Visit [Releases](/docs/releases/index) to download the CockroachDB archive for the architecture of your macOS host. The archive contains the `cockroach` binary and the supporting libraries that are used to provide [spatial features](/docs/v26.4/spatial-data-overview). You can download the binary using a web browser or you can copy the link and use a utility like `curl` to download it. If you download the ARM binary using a web browser and you plan to use CockroachDB's spatial features, an additional step is required before you can install the library, as outlined in the next step. Extract the archive and optionally copy the `cockroach` binary into your `PATH` so you can execute [cockroach commands](/docs/v26.4/cockroach-commands) from any shell. If you get a permission error, use `sudo`. If you plan to use CockroachDB's [spatial features](/docs/v26.4/spatial-data-overview), you must complete all of the following steps. Otherwise, your installation is now complete. 2. CockroachDB uses custom-built versions of the [GEOS](/docs/v26.4/architecture/glossary#geos) libraries. To install those libraries: 1. Note that [spatial features are currently disabled for Mac ARM users](/docs/v26.4/spatial-data-overview#known-limitations), for whom these steps do not apply. For an upcoming patch release where this functionality is reenabled, if you downloaded the CockroachDB ARM binary archive using a web browser, macOS flags the GEOS libraries in the extracted archive as quarantined. This flag must be removed before CockroachDB can use the libraries. To remove the quarantine flag from the libraries: This step is not required for Intel systems. 2. Copy these libraries to one of the locations where CockroachDB expects to find them. By default, CockroachDB looks for external libraries in `/usr/local/lib/cockroach` or a `lib` subdirectory of the CockroachDB binary's current directory. If you place these libraries in another location, you must pass the location in the [`--spatial-libs` flag to `cockroach start`](/docs/v26.4/cockroach-start#flags-spatial-libs). The instructions below assume the `/usr/local/lib/cockroach` location. 1. Create the directory where the external libraries will be stored: ``` mkdir -p /usr/local/lib/cockroach ``` 2. Copy the library files to the directory: ``` cp -i cockroach-v26.4.darwin-10.9-amd64/lib/libgeos.dylib /usr/local/lib/cockroach/ ``` ``` cp -i cockroach-v26.4.darwin-10.9-amd64/lib/libgeos_c.dylib /usr/local/lib/cockroach/ ``` If you get a permissions error, prefix the command with `sudo`. 3. Verify that CockroachDB can execute spatial queries. 1. Make sure the `cockroach` binary you just installed is the one that runs when you type `cockroach` in your shell: ``` which cockroach ``` ``` /usr/local/bin/cockroach ``` 2. Start a temporary, in-memory cluster using [`cockroach demo`](/docs/v26.4/cockroach-demo): ``` cockroach demo ``` 3. In the demo cluster's interactive SQL shell, run the following command to test that the spatial libraries have loaded properly: ``` > SELECT ST_IsValid(ST_MakePoint(1,2)); ``` You should see the following output: If your `cockroach` binary is not properly accessing the dynamically linked C libraries in `/usr/local/lib/cockroach`, it will output an error message like the one below. ``` ERROR: st_isvalid(): geos: error during GEOS init: geos: cannot load GEOS from dir "/usr/local/lib/cockroach": failed to execute dlopen Failed running "sql" ``` * Keep up-to-date with CockroachDB releases and best practices: ## Use Kubernetes To orchestrate CockroachDB using [Kubernetes](https://kubernetes.io/), use the official [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview#cockroachdb-operator). You can evaluate a CockroachDB Kubernetes deployment on a local machine with [minikube](https://minikube.sigs.k8s.io/docs/start/). ## Use Docker > [!CAUTION] > > Running a stateful application like CockroachDB in Docker is more complex and error-prone than most uses of Docker. Unless you are very experienced with Docker, we recommend starting with a different installation and deployment method. > CockroachDB's Docker images are [multi-platform images](https://docs.docker.com/build/building/multi-platform/) that contain binaries for both Intel and ARM. Multi-platform images do not take up additional space on your Docker host. > Experimental images are not qualified for production use and not eligible for support or uptime SLA commitments. > > 1. Install a container runtime, such as [Docker Desktop](https://docs.docker.com/desktop/). > 2. Verify that the runtime service is installed correctly and running in the background. Refer to the runtime's documentation. For Docker, start a terminal and run `docker version`. If you get an error, verify your installation and try again. > 3. Visit [Docker Hub](https://hub.docker.com/r/cockroachdb/cockroach) and decide which image tag to pull. Releases are rolled out gradually. Docker images for a new release are published when other binary artifacts are published. The following tag formats are commonly used, although other tags are available. | Tag | Example | Description | | - | - | - | | An exact patch | \`\` | Pins a cluster to an exact patch. The cluster is upgraded to a newer patch or major version only when you pull a newer tag. | | Latest patch within a major version | `latest-v26.4` | Automatically updates a cluster to the latest patch of the version you specify. This tag is recommended in production, because it keeps your cluster updated within a major version but does not automatically upgrade your cluster to a new major version. | | `latest` | The latest patch within the latest major version. This is the default if you do not specify a tag. It updates your cluster automatically to each new patch and major version, and is not recommended in production. | | Copy the tag you want to pull. 1. Pull the image. Replace `{TAG}` with the tag from the previous step. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} docker pull cockroachdb/cockroach:{TAG} ``` 1. Start a cluster by starting the container on each node using `docker start`. The default command is `cockroach start`. Pass your desired flags as the final argument. For details, refer to [Deploy a local container in Docker](/docs/v26.4/start-a-local-cluster-in-docker). ## Build from source See the [public wiki](https://wiki.crdb.io/wiki/spaces/CRDB/pages/181338446/Getting+and+building+CockroachDB+from+source) for guidance. When building on the ARM architecture, refer to [Limitations](#limitations). ## Limitations CockroachDB runtimes built for the ARM architecture have the following limitations: * CockroachDB on ARM for macOS is **experimental** and is not yet qualified for production use and not eligible for support or uptime SLA commitments. * Clusters with a mix of Intel and ARM nodes are untested. Cockroach Labs recommends that all cluster nodes have identical CockroachDB versions, hardware, and software. * Floating point operations may yield different results on ARM than on Intel, particularly [Fused Multiply Add (FMA) intrinsics](https://developer.arm.com/documentation/dui0375/g/Compiler-specific-Features/Fused-Multiply-Add--FMA--intrinsics). * When [building from source](#install-source) on ARM, consider disabling FMA intrinsics in your compiler. For GCC, refer to [Options That Control Optimization](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) in the GCC documentation. ## What's next? * If you're just getting started with CockroachDB: * [Create a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?experience=enterprise) where you can [generate and manage licenses](/docs/v26.4/licensing-faqs) for CockroachDB installations * [Start a cluster locally](/docs/v26.4/start-a-local-cluster) and talk to it via the built-in SQL client * [Learn more about CockroachDB SQL](/docs/v26.4/learn-cockroachdb-sql) * [Explore CockroachDB features](/docs/v26.4/demo-replication-and-rebalancing) like automatic replication, rebalancing, and fault tolerance * If you're ready to run CockroachDB in production: * Review the [Production Checklist](/docs/v26.4/recommended-production-settings) * [Deploy CockroachDB manually](/docs/v26.4/manual-deployment) or [use an orchestration system like Kubernetes](/docs/v26.4/kubernetes-overview) ## Limitations On macOS ARM systems, [spatial features](/docs/v26.4/spatial-data-overview) are disabled due to an issue with macOS code signing for the [GEOS](https://libgeos.org/) libraries. Users needing spatial features on an ARM Mac may instead [run the Intel binary](#install-the-binary) or use the[Docker container image](#use-docker). # Install CockroachDB on Windows Source: https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-windows > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the [Cloud Quickstart](/docs/cockroachcloud/quickstart). > **This page refers to CockroachDB v26.4.** For the latest supported release, refer to the [Release Support Policy](/docs/releases/release-support-policy). > CockroachDB executable for Windows is experimental and not suitable for production deployments. Windows 8 or higher is required. > Use one of the options below to install CockroachDB. To upgrade an existing cluster, refer to [Upgrade to v26.4](/docs/v26.4/upgrade-cockroach-version). ## Download the executable You can download and install CockroachDB for Windows in two ways. Either: * **Recommended**: Visit [Releases](/docs/releases/index?filters=windows) to download CockroachDB. The archive contains the `cockroach.exe` binary. Extract the archive and optionally copy the `cockroach.exe` binary into your `PATH` so you can execute [cockroach commands](/docs/v26.4/cockroach-commands) from any shell. Releases are rolled out gradually, so the latest version may not yet be downloadable. * Instead of downloading the binary directly, you can use PowerShell to download and install CockroachDB: 1. Visit [Releases](/docs/releases/index) and make a note of the full version of CockroachDB to install, such as . Releases are rolled out gradually, so the latest version may not yet be downloadable. 2. Save the following PowerShell script and replace the following: * `VERSION`: the full version of CockroachDB to download, such as \`\`. Replace this value in both the `Invoke-WebRequest` statement and the `Copy-Item` statement. * `{ INSTALL_DIRECTORY }`: the local file path where the `cockroachdb.exe` executable will be installed. Replace the value in both the `Destination` argument and the `$Env:PATH` statement, which adds the destination directory to your `PATH`. ```powershell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ErrorActionPreference = "Stop"; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;$ProgressPreference = 'SilentlyContinue'; $null = New-Item -Type Directory -Force $env:appdata/cockroach; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/cockroach-VERSION.windows-6.2-amd64.zip -OutFile cockroach.zip; Expand-Archive -Force -Path cockroach.zip; Copy-Item -Force "cockroach/cockroach-VERSION.windows-6.2-amd64/cockroach.exe" -Destination $env:{ INSTALL_DIRECTORY };$Env:PATH += ";$env:{ INSTALL_DIRECTORY }" ``` 1. Run the PowerShell script. To run a PowerShell script from a file, use syntax like: ```powershell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} powershell.exe -Command "{path_to_script}" ``` 1. Check that the installation succeeded and that you can run `cockroach` commands: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach version ``` ## Use Kubernetes To orchestrate CockroachDB using [Kubernetes](https://kubernetes.io/), use the official [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview#cockroachdb-operator). You can evaluate a CockroachDB Kubernetes deployment on a local machine with [minikube](https://minikube.sigs.k8s.io/docs/start/). ## Use Docker > [!CAUTION] > > This section shows how to install CockroachDB on a Windows host using Docker. On a Linux or Windows Docker host, the image creates a Linux container. > Running a stateful application like CockroachDB in Docker is more complex and error-prone than most uses of Docker. Unless you are very experienced with Docker, we recommend starting with a different installation and deployment method. > Docker images are [multi-platform images](https://docs.docker.com/build/building/multi-platform/) that contain binaries for both Intel and ARM. Multi-platform images do not take up additional space on your Docker host. > Intel binaries can run on ARM systems, but with a significant reduction in performance. > > 1. Install [Docker for Windows](https://docs.docker.com/docker-for-windows/install/). > Docker for Windows requires 64-bit Windows 10 Pro and Microsoft Hyper-V. Refer to the [official documentation](https://docs.docker.com/docker-for-windows/install/#what-to-know-before-you-install) for more details. If your system does not satisfy the stated requirements, you can try using [Docker Toolbox](https://docs.docker.com/toolbox/overview/). > 2. In PowerShell, confirm that Docker is running in the background: > > ```powershell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > docker version > ``` > > If you see an error, verify your Docker for Windows installation, then try again. > > 1. [Enable synchronized drive sharing](https://docs.docker.com/desktop/synchronized-file-sharing/) so you can mount local directories as data volumes to persist node data after containers are stopped or deleted. > 2. Visit [Docker Hub](https://hub.docker.com/layers//) and make a note of the full version of CockroachDB to pull. Releases are rolled out gradually, so the latest version may not yet be available. Using the `latest` tag is not recommended; to pull the latest release within a major version, use a tag like `latest-v26.4`. The following command always pulls the \`\` image. > > ```powershell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > docker pull : > ``` > > Keep up-to-date with CockroachDB releases and best practices: ## What's next? * If you're just getting started with CockroachDB: * [Create a CockroachDB Cloud account](https://cockroachlabs.cloud/signup?experience=enterprise) where you can [generate and manage licenses](/docs/v26.4/licensing-faqs) for CockroachDB installations * [Start a cluster locally](/docs/v26.4/start-a-local-cluster) and talk to it via the built-in SQL client * [Learn more about CockroachDB SQL](/docs/v26.4/learn-cockroachdb-sql) * [Explore CockroachDB features](/docs/v26.4/demo-replication-and-rebalancing) like automatic replication, rebalancing, and fault tolerance * If you're ready to run CockroachDB in production: * Review the [Production Checklist](/docs/v26.4/recommended-production-settings) * [Deploy CockroachDB manually](/docs/v26.4/manual-deployment) or [use an orchestration system like Kubernetes](/docs/v26.4/kubernetes-overview) # Agent Skills for CockroachDB Source: https://docs.cockroachlabs.com/docs/stable/agent-skills Cockroach Labs provides a public [cockroachdb-skills](https://github.com/cockroachlabs/cockroachdb-skills) repository with a curated collection of Agent Skills for CockroachDB. These skills encode operational expertise so that AI agents, automation systems, and developer tools can perform production-grade CockroachDB operations. ## What is a CockroachDB Agent Skill? A CockroachDB Agent Skill: * Encodes operational expertise for a specific task or workflow. * Follows the [Agent Skills Specification](https://agentskills.io/specification). * Is machine-executable, with clear inputs, outputs, and safety guardrails. * Links to authoritative CockroachDB documentation rather than duplicating it. Skills live under [the repository's `skills/` directory](https://github.com/cockroachlabs/cockroachdb-skills/tree/main/skills). ## Skill domains Skills are organized into the following operational domains: * Onboarding and migrations * Application development * Performance and scaling * Operations and lifecycle * Resilience and Disaster Recovery (DR) * Observability and Diagnostics * Security and Governance * Integrations and Ecosystem * Cost and usage management ## See also * [CockroachDB and AI](/docs/v26.4/cockroachdb-and-ai) * [CockroachDB Cloud MCP Server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server) * [CockroachDB Docs MCP Server](/docs/v26.4/docs-mcp-integration) * [CockroachDB Skills repository](https://github.com/cockroachlabs/cockroachdb-skills) # Authenticate to CockroachDB Self-Hosted Clusters Source: https://docs.cockroachlabs.com/docs/stable/authentication Authentication refers to the act of verifying the identity of the other party in communication. CockroachDB requires TLS 1.3 digital certificates for inter-node authentication and accepts TLS 1.2 and TLS 1.3 certificates for client-node authentication. This document discusses how CockroachDB uses digital certificates and what your options are for configuring user authentication for SQL clients and the DB Console UI. It also offers a [conceptual overview](#background-on-public-key-cryptography-and-digital-certificates) of public key cryptography and digital certificates. * If you are familiar with public key cryptography and digital certificates, then reading the [Using digital certificates with CockroachDB](#using-digital-certificates-with-cockroachdb) section should be enough. * If you are unfamiliar with public key cryptography and digital certificates, you might want to skip over to the [conceptual overview](#background-on-public-key-cryptography-and-digital-certificates) first and then come back to the [Using digital certificates with CockroachDB](#using-digital-certificates-with-cockroachdb) section. * If you want to know how to create CockroachDB security certificates, see [Create Security Certificates](/docs/v26.4/cockroach-cert). ## Connecting to a CockroachDB cluster Users may connect with CockroachDB self-hosted clusters in 2 main ways: * SQL clients connections, including the CockroachDB CLI client and the [various supported drivers and ORMs](/docs/v26.4/install-client-drivers), connect directly to CockroachDB clusters using the [CockroachDB SQL interface](/docs/v26.4/sql-feature-support). * A read-only monitoring service, which provides cluster and database details, and information useful for troubleshooting and performance tuning. Each CockroachDB node also acts as an HTTP server, providing both a [browser UI DB console](/docs/v26.4/ui-overview) and the [cluster API](/docs/v26.4/cluster-api), which provides much of the same information as the DB console, but as a rest API suitable for programmatic access. ## Using digital certificates with CockroachDB Each CockroachDB node in a secure cluster must have a **node certificate**, which is a TLS 1.3 certificate. This certificate is multi-functional; the same certificate is presented irrespective of whether the node is acting as a server or a client. The nodes use these certificates to establish secure connections with clients and with other nodes. Node certificates have the following requirements: * The hostname or address (IP address or DNS name) used to reach a node, either directly or through a load balancer, must be listed in the **Common Name** or **Subject Alternative Names** fields of the certificate: * The values specified in [`--listen-addr`](/docs/v26.4/cockroach-start#networking) and [`--advertise-addr`](/docs/v26.4/cockroach-start#networking) flags, or the node hostname and fully qualified hostname if not specified * Any host addresses/names used to reach a specific node * Any load balancer addresses/names or DNS aliases through which the node could be reached * `localhost` and local address if connections are made through the loopback device on the same host * CockroachDB must be configured to trust the certificate authority that signed the certificate. Based on your security setup, you can use the [`cockroach cert` commands](/docs/v26.4/cockroach-cert), [`openssl` commands](/docs/v26.4/create-security-certificates-openssl), or a [custom CA](/docs/v26.4/create-security-certificates-custom-ca) to generate all the keys and certificates. A CockroachDB cluster consists of multiple nodes and clients. The nodes can communicate with each other, with the SQL clients, and the DB Console. In client-node SQL communication and client-UI communication, the node acts as a server, but in inter-node communication, a node may act as a server or a client. Hence authentication in CockroachDB involves: * Node authentication using [TLS 1.3](https://wikipedia.org/wiki/Transport_Layer_Security) digital certificates. * Client authentication using TLS digital certificates, passwords, or [GSSAPI authentication](/docs/v26.4/gssapi_authentication) (for Enterprise users). > [!NOTE] > > If you manage your own Certificate Authority (CA) infrastructure, CockroachDB supports mapping between the Subject field of your [X.509 certificates](https://en.wikipedia.org/wiki/X.509) and SQL [roles](/docs/v26.4/security-reference/authorization#roles). For more information, see [Certificate-based authentication using multiple values from the X.509 Subject field](/docs/v26.4/certificate-based-authentication-using-the-x509-subject-field). ### Node authentication To set up a secure cluster without using an existing certificate authority, you'll need to generate the following files: * CA certificate * Node certificate and key * (Optional) UI certificate and key ### Client authentication CockroachDB offers the following methods for client authentication: * **Client certificate and key authentication**, which is available to all users. To ensure the highest level of security, we recommend only using client certificate and key authentication. If you use your own Certificate Authority (CA), you can also map SQL users to values in the certificate's Subject field or Subject Alternative Name (SAN) entries. Refer to [Certificate-based authentication using multiple values from the X.509 Subject field](/docs/v26.4/certificate-based-authentication-using-the-x509-subject-field). Example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --certs-dir=certs --user=jpointsman ``` * **Password authentication**, which is available to users and roles who you've created passwords for. Password creation is supported only in secure clusters. Example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --certs-dir=certs --user=jpointsman ``` ``` # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # Enter password: ``` The client still needs the CA certificate to validate the certificate of the node. > [!TIP] > > For improved performance, CockroachDB securely caches password authentication information for users. To limit the authentication latency of users logging into a new session, we recommend that you run bulk `ROLE` operations ([`CREATE ROLE`](/docs/v26.4/create-role), [`ALTER ROLE`](/docs/v26.4/alter-role), [`DROP ROLE`](/docs/v26.4/drop-role)) inside a transaction, and run any regularly-scheduled `ROLE` operations together, rather than at different times throughout the day. * **Password authentication without TLS** For deployments where transport security is already handled at the infrastructure level (e.g., IPSec with DMZ), and TLS-based transport security is not possible or not desirable, CockroachDB now supports delegating transport security to the infrastructure with the flag `--accept-sql-without-tls` for [`cockroach start`](/docs/v26.4/cockroach-start#security). The `--accept-sql-without-tls` flag is in [preview](/docs/releases/cockroachdb-feature-availability). With this flag, SQL clients can establish a session over TCP without a TLS handshake. They still need to present valid authentication credentials, for example a password in the default configuration. Different authentication schemes can be further configured as per `server.host_based_authentication.configuration`. Example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --user=jpointsman --insecure ``` ``` # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # Enter password: ``` * [**Single sign-on authentication to DB Console**](/docs/v26.4/sso-db-console). CockroachDB supports OpenID Connect (OIDC) for authenticating users to the DB Console. You can enable [automatic user provisioning](/docs/v26.4/sso-db-console#manage-auto-provisioned-users) and [automatic role synchronization](/docs/v26.4/oidc-authorization) based on group memberships from your identity provider. * [**JWT authentication for SQL clients**](/docs/v26.4/sso-sql). CockroachDB supports JSON Web Token (JWT) authentication for SQL client connections. You can enable [automatic user provisioning](/docs/v26.4/sso-sql#configure-user-provisioning) and [automatic role synchronization](/docs/v26.4/jwt-authorization) based on group claims in JWT tokens. * [**OAuth (SASL OAUTHBEARER) authentication for SQL clients**](/docs/v26.4/oauth-authentication). CockroachDB supports SASL OAUTHBEARER (RFC 7628) authentication for SQL client connections, compatible with PostgreSQL 18 clients such as `psql`. Clients present an OAuth 2.0 bearer token, or `cockroach sql` can obtain one interactively with the OAuth device flow. You can enable [automatic user provisioning](/docs/v26.4/oauth-authentication#step-4-configure-user-creation) and [automatic role synchronization](/docs/v26.4/oauth-authentication#step-5-enable-group-based-authorization-optional) based on group claims in the token. * [**GSSAPI authentication**](/docs/v26.4/gssapi_authentication). ### Using `cockroach cert` or `openssl` commands You can use the [`cockroach cert` commands](/docs/v26.4/cockroach-cert) or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to create the CA certificate and key, and node and client certificates and keys. Note that the node certificate created using `cockroach cert` or`openssl` is multi-functional, which means that the same certificate is presented irrespective of whether the node is acting as a server or a client. Thus all nodes must have the following: * `CN=node` for the special user `node` when the node acts as a client. * All IP addresses and DNS names for the node must be listed in the `Subject Alternative Name` field for when the node acts as a server. CockroachDB also supports [wildcard notation in DNS names](https://wikipedia.org/wiki/Wildcard_certificate). **Node key and certificates** A node must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate created using the `cockroach cert` command. | | `node.crt` | Server certificate created using the `cockroach cert` command. `node.crt` must have `CN=node` and the list of IP addresses and DNS names listed in the `Subject Alternative Name` field. CockroachDB also supports [wildcard notation in DNS names](https://wikipedia.org/wiki/Wildcard_certificate). Must be signed by the CA represented by `ca.crt`. | | `node.key` | Server key created using the `cockroach cert` command. | **Client key and certificates** A client must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate created using the `cockroach cert` command. | | `client. [!CAUTION] > > We do not recommend you use split CA certificates unless your organizational security practices mandate you to do so. You might encounter situations where you need separate CAs to sign and verify node and client certificates. In that case, you would need two CAs and their respective certificates and keys: `ca.crt` and `ca-client.crt`. **Node key and certificates** A node must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate to verify node certificates. | | `ca-client.crt` | CA certificate to verify client certificates. | | `node.crt` | Node certificate for when node acts as server. All IP addresses and DNS names for the node must be listed in the `Subject Alternative Name`. CockroachDB also supports [wildcard notation in DNS names](https://wikipedia.org/wiki/Wildcard_certificate). Must be signed by the CA represented by `ca.crt`. | | `node.key` | Server key corresponding to `node.crt`. | | `client.node.crt` | Node certificate for when node acts as client. This certificate must be signed by the CA represented by `ca-client.crt`. Must have `CN=node`. | | `client.node.key` | Client key corresponding to `client.node.crt`. | Optionally, if you have a certificate issued by a public CA to securely access the DB Console, you need to place the certificate and key (`ui.crt` and `ui.key` respectively) in the directory specified by the `--certs-dir` flag. **Client key and certificates** A client must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate. | | `client. [!NOTE] > > CockroachDB supports the [TLS 1.3 and TLS 1.2](https://wikipedia.org/wiki/Transport_Layer_Security) encryption for SQL clients. Starting in CockroachDB v22.2, only cipher suites currently recommended by the IETF ([RFC 8447](https://datatracker.ietf.org/doc/html/rfc8447)) are enabled by default. In v22.2.4 and above, the environment variable `COCKROACH_TLS_ENABLE_OLD_CIPHER_SUITES` can be used to revert to the cipher suite configuration used in version 22.1. This environment variable is not available in v22.2.0-v22.2.3. You should set this environment variable only if you cannot use one of the default cipher suites, but you can use one of the disabled ones. > > CockroachDB supports the [TLS 1.3 and TLS 1.2](https://wikipedia.org/wiki/Transport_Layer_Security) encryption for SQL clients. Only cipher suites currently recommended by the IETF ([RFC 8447](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4)) are enabled by default. The environment variable `COCKROACH_TLS_ENABLE_OLD_CIPHER_SUITES` can be used to revert to the cipher suite configuration used prior to v22.2. You should set this environment variable only if you cannot use one of the default cipher suites, but you can use one of the disabled ones. > > SQL clients, intermediate proxies, or load balancers that do not support any cipher suites that CockroachDB supports will be unable to connect to CockroachDB clusters. For the full list of supported cipher suites, refer to [Supported cipher suites](https://cockroachlabs.com/docs/stable/authentication#supported-cipher-suites). Authentication refers to the act of verifying the identity of the other party in communication. CockroachDB uses TLS 1.3 digital certificates for inter-node authentication, and your choice of TLS 1.2 and TLS 1.3 certificates for client-node authentication (defaulting to TLS 1.3, if supported by the client). These authentication methods require a certificate authority (CA) as well as keys and certificates for nodes, clients, and, optionally, the [DB Console](#using-a-public-ca-certificate-to-access-the-db-console-for-a-secure-cluster). To understand how CockroachDB uses digital certificates, let's first understand what each of these terms means. Consider two people: Amy and Rosa, who want to communicate securely over an insecure computer network. The traditional solution is to use symmetric encryption that involves encrypting and decrypting a plaintext message using a shared key. Amy encrypts her message using the key and sends the encrypted message across the insecure channel. Rosa decrypts the message using the same key and reads the message. This seems like a logical solution until you realize that you need a secure communication channel to send the encryption key. To solve this problem, cryptographers came up with **asymmetric encryption** to set up a secure communication channel over which an encryption key can be shared. ### Asymmetric encryption Asymmetric encryption involves a pair of keys instead of a single key. The two keys are called the **public key** and the **private key**. The keys consist of very long numbers linked mathematically in a way such that a message encrypted using a public key can only be decrypted using the private key and vice versa. The message cannot be decrypted using the same key that was used to encrypt the message. So going back to our example, Amy and Rosa both have their own public-private key pairs. They keep their private keys safe with themselves and publicly distribute their public keys. Now when Amy wants to send a message to Rosa, she requests Rosa's public key, encrypts the message using Rosa’s public key, and sends the encrypted message. Rosa uses her own private key to decrypt the message. But what if a malicious imposter intercepts the communication? The imposter might pose as Rosa and send their public key instead of Rosa’s. There's no way for Amy to know that the public key she received isn’t Rosa’s, so she would end up using the impostor's public key to encrypt the message and send it to the imposter. The imposter can use their own private key and decrypt and read the message, thus compromising the secure communication channel between Amy and Rosa. To prevent this security risk, Amy needs to be sure that the public key she received was indeed Rosa’s. That’s where the Certificate Authority (CA) comes into the picture. ### Certificate authority Certificate authorities are established entities with their own public and private key pairs. They act as a root of trust and verify the identities of the communicating parties and validate their public keys. CAs can be public and paid entities (e.g., GeoTrust and Comodo), or public and free CAs (e.g., Let’s Encrypt), or your own organizational CA (e.g., CockroachDB CA). The CAs' public keys are typically widely distributed (e.g., your browser comes preloaded with certs from popular CAs like DigiCert, GeoTrust, and so on). Think of the CA as the passport authority of a country. When you want to get your passport as your identity proof, you submit an application to your country's passport authority. The application contains important identifying information about you: your name, address, nationality, date of birth, and so on. The passport authority verifies the information they received and validates your identity. They then issue a document - the passport - that can be presented anywhere in the world to verify your identity. For example, the TSA agent at the airport does not know you and has no reason to trust you are who you say you are. However, they trust the passport authority and thus accept your identity as presented on your passport because it has been verified and issued by the passport authority. Going back to our example and assuming that we trust the CA, Rosa needs to get her public key verified by the CA. She sends a CSR (Certificate Signing Request) to the CA that contains her public key and relevant identifying information. The CA will verify that it is indeed Rosa’s public key and information, *sign* the CSR using the CA's own private key, and generate a digital document called the **digital certificate**. In our passport analogy, this is Rosa's passport containing verified identifying information about her and trusted by everyone who trusts the CA. The next time Rosa wants to establish her identity, she will present her digital certificate. ### Digital certificate A public key is shared using a digital certificate signed by a CA using the CA's private key. The digital certificate contains: * The certificate owner’s public key * Information about the certificate owner * The CA's digital signature ### Digital signature The CA's digital signature works as follows: The certificate contents are put through a mathematical function to create a **hash value**. This hash value is encrypted using the CA's private key to generate the **digital signature**. The digital signature is added to the digital certificate. In our example, the CA adds their digital signature to Rosa's certificate validating her identity and her public key. As discussed [earlier](#certificate-authority), the CA's public key is widely distributed. In our example, Amy already has the CA's public key. Now when Rosa presents her digital certificate containing her public key, Amy uses the CA's public key to decrypt the digital signature on Rosa's certificate and gets the hash value encoded in the digital signature. Amy also generates the hash value for the certificate on her own. If the hash values match, then Amy can be sure that the certificate and hence the public key it contains indeed belongs to Rosa; otherwise, she can determine that the communication channel has been compromised and refuse further contact. ### How it all works together Let's see how the digital certificate is used in client-server communication: The client (e.g., a web browser) has the CA certificate (containing the CA's public key). When the client receives a server's certificate signed by the same CA, it can use the CA certificate to verify the server's certificate, thus validating the server's identity, and securely connect to the server. The important thing here is that the client needs to have the CA certificate. If you use your own organizational CA instead of a publicly established CA, you need to make sure you distribute the CA certificate to all the clients. ## Supported cipher suites CockroachDB supports the [TLS 1.3 and TLS 1.2](https://wikipedia.org/wiki/Transport_Layer_Security) encryption for SQL clients. However, only cipher suites currently recommended by the IETF ([RFC 8447](https://datatracker.ietf.org/doc/html/rfc8447)) are enabled by default. The environment variable `COCKROACH_TLS_ENABLE_OLD_CIPHER_SUITES` can be used to revert to the cipher suite configuration used prior to version 22.2. You should set this environment variable only if you cannot use one of the default cipher suites, but you can use one of the disabled ones. By default, CockroachDB negotiates TLS 1.3 for client connections when supported by the client. If the client does not support TLS 1.3, the connection will fall back to TLS 1.2. To restrict your cluster to only allow connections using specific cipher suites, use the [`--tls-cipher-suites`](/docs/v26.4/cockroach-start#tls-cipher-suites) startup flag with the `cockroach start` command. This setting applies to all incoming SQL, RPC, and HTTP connections. The following cipher suites are enabled by default: * `TLS_AES_128_GCM_SHA256`, * `TLS_AES_256_GCM_SHA384`, * `TLS_CHACHA20_POLY1305_SHA256` * `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256` * `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` * `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` * `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` * `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256` * `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` The following cipher suites are rejected by default because they are not recommended by the IETF ([RFC 8447](https://datatracker.ietf.org/doc/html/rfc8447)): * `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA` * `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA` * `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA` * `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA` * `TLS_RSA_WITH_AES_128_GCM_SHA256` * `TLS_RSA_WITH_AES_256_GCM_SHA384` * `TLS_RSA_WITH_AES_128_CBC_SHA` * `TLS_RSA_WITH_AES_256_CBC_SHA` ### TLS handshake timeouts CockroachDB bounds the TLS handshake on the inbound connections listed in the following table, so a peer that stalls mid-handshake is disconnected when the bound elapses. The following environment variables control these bounds. Set them on each node before running `cockroach start`. | Environment variable | Default | Description | | - | - | - | | `COCKROACH_TLS_HANDSHAKE_TIMEOUT` | `10s` | Bounds the TLS handshake on inbound connections between nodes that use the new RPC framework, and on inbound SQL connections when a cipher suite allowlist is configured with [`--tls-cipher-suites`](/docs/v26.4/cockroach-start#tls-cipher-suites). | | `COCKROACH_RPC_SERVER_CONNECTION_TIMEOUT` | `30s` | Bounds connection establishment (the TLS handshake plus HTTP/2 setup) on inbound [gRPC](/docs/v26.4/architecture/distribution-layer#grpc) connections between nodes. This replaces the implicit limit of 120 seconds in earlier versions. | The HTTP interface (DB Console) uses a fixed TLS handshake timeout that cannot be changed. ## Supported key exchange mechanisms For information about supported TLS 1.3 key exchange mechanisms, including post-quantum cryptography support, see [Post-quantum cryptography support in CockroachDB](/docs/v26.4/security-reference/transport-layer-security#post-quantum-cryptography-support-in-cockroachdb). ## See also * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Local Deployment](/docs/v26.4/secure-a-cluster) * [`cockroach` Commands Overview](/docs/v26.4/cockroach-commands) * [Certificate-based authentication using multiple values from the X.509 Subject field](/docs/v26.4/certificate-based-authentication-using-the-x509-subject-field) * [`ALTER ROLE ... SUBJECT`](/docs/v26.4/alter-role#set-the-subject-role-option-for-certificate-based-authentication) * [`CREATE ROLE ... SUBJECT`](/docs/v26.4/create-role#set-the-subject-role-option-for-certificate-based-authentication) * [`cockroach cert`](/docs/v26.4/cockroach-cert) * [`cockroach auth-session`](/docs/v26.4/cockroach-auth-session) * [GSSAPI Authentication](/docs/v26.4/gssapi_authentication) * [Single Sign-on (SSO) for DB Console](/docs/v26.4/sso-db-console) * [Cluster Single Sign-on (SSO) using JWTs](/docs/v26.4/sso-sql) * [SASL OAUTHBEARER (OAuth 2.0) Authentication for SQL Clients](/docs/v26.4/oauth-authentication) * [JWT Authorization](/docs/v26.4/jwt-authorization) * [OIDC Authorization](/docs/v26.4/oidc-authorization) * [LDAP Authorization](/docs/v26.4/ldap-authorization) * [SQL Authentication](/docs/v26.4/security-reference/authentication) * [Cloud Storage Authentication](/docs/v26.4/cloud-storage-authentication) # Manage Cluster User Authorization Source: https://docs.cockroachlabs.com/docs/stable/authorization This page documents procedures for managing the lifecycle of SQL users and roles on CockroachDB clusters. Procedures for managing access are covered in [Managing Access in CockroachDB Cloud](/docs/cockroachcloud/managing-access). > [!NOTE] > > The concept of *Organization user* is distinct from Authorization of *SQL user/role* on clusters is distinct from authorization of CockroachDB Cloud users within CockroachDB Cloud organizations. > > Learn more: [Overview of the CockroachDB Cloud authorization model](/docs/cockroachcloud/authorization#overview-of-the-cockroachdb-cloud-authorization-model) > For reference documentation and explanation of related concepts, see [Security Reference — Authorization](/docs/v26.4/security-reference/authorization). ## Create CockroachDB users Use the [`CREATE USER`](/docs/v26.4/create-user) and [`DROP USER`](/docs/v26.4/drop-user) statements to create and remove users, the [`ALTER USER`](/docs/v26.4/alter-user) statement to add or change a user's password and role options, the [`GRANT`](/docs/v26.4/grant) and [`REVOKE`](/docs/v26.4/revoke) statements to manage the user’s privileges, and the [`SHOW USERS`](/docs/v26.4/show-users) statement to list users. A new user must be granted the required privileges for each database and table that the user needs to access. > [!NOTE] > > By default, a new user belongs to the `public` role and has no privileges other than those assigned to the `public` role. ## Create and manage roles For examples showing how to create and manage your cluster's users and roles, see the following documentation: | Statement | Description | | - | - | | [`CREATE ROLE`](/docs/v26.4/create-role) | Create SQL roles. | | [`DROP ROLE`](/docs/v26.4/drop-role) | Remove one or more SQL roles. | | [`ALTER ROLE`](/docs/v26.4/alter-role) | Change passwords, role options, and default session variables for a role. | | [`CREATE USER`](/docs/v26.4/create-user) | Create SQL users. | | [`DROP USER`](/docs/v26.4/create-user) | Remove one or more SQL users. | | [`ALTER USER`](/docs/v26.4/alter-user) | Change passwords and role options for a user. | | [`GRANT`](/docs/v26.4/grant) | Manage each role or user's SQL privileges for interacting with specific databases and tables, or add a role or user as a member to a role. | | [`REVOKE`](/docs/v26.4/revoke) | Revoke privileges from users and/or roles, or revoke a role or user's membership to a role. | | [`SHOW ROLES`](/docs/v26.4/show-roles) | List the roles for all databases. | | [`SHOW GRANTS`](/docs/v26.4/show-grants) | List the privileges granted to users. | ## See also * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [SQL Statements](/docs/v26.4/sql-statements) * [`CREATE USER`](/docs/v26.4/create-user) * [`ALTER USER`](/docs/v26.4/alter-user) * [`DROP USER`](/docs/v26.4/drop-user) * [`SHOW USERS`](/docs/v26.4/show-users) * [`CREATE ROLE`](/docs/v26.4/create-role) * [`ALTER ROLE`](/docs/v26.4/alter-role) * [`DROP ROLE`](/docs/v26.4/drop-role) * [`SHOW ROLES`](/docs/v26.4/show-roles) * [`GRANT`](/docs/v26.4/grant) * [`REVOKE`](/docs/v26.4/revoke) * [`SHOW GRANTS`](/docs/v26.4/show-grants) # Certificate-based authentication using multiple values from the X.509 Subject field Source: https://docs.cockroachlabs.com/docs/stable/certificate-based-authentication-using-the-x509-subject-field For customers that need to use their established Certificate Authority (CA) infrastructure to manage SQL user authentication, CockroachDB supports mapping of SQL user [roles](/docs/v26.4/security-reference/authorization#roles) to values in the Subject field of the [X.509 certificate](https://en.wikipedia.org/wiki/X.509) used for [TLS authentication](/docs/v26.4/security-reference/transport-layer-security#what-is-transport-layer-security-tls). This mapping (hereafter referred to as "Subject mapping") can be used to automate the synchronization of SQL user roles with specific certificate attributes, leading to improved scalability of access control mechanisms. Subject mapping is useful if: * You run your own [Certificate Authority (CA)](/docs/v26.4/security-reference/transport-layer-security#certificates-signing-trust-and-authority) infrastructure. * You need to use your existing CA infrastructure to manage [SQL user authentication](/docs/v26.4/create-user#user-authentication). * You need to use the same CA for multiple CockroachDB clusters. For instructions showing how to map SQL user roles to values in the Subject field of the X.509 certificate, see the [Example](#example). ## Related functionality Prior to CockroachDB v24.1, it was only safe to use certificates generated by CAs that placed restrictions on the `CommonName` field (so that only authorized users could get a cert with `CommonName=root`, for example). That meant that mapping the certificate principals to IP addresses, DNS names, and SQL users required using [the `--cert-principal-map` flag](/docs/v26.4/cockroach-start), which was first added in v20.1. That approach still works, but is superseded by the functionality described on this page, which should be much easier to use since you do not need to restart nodes [when you add or remove users](#step-3-set-the-subject-role-option-using-create-role-or-alter-role-to-match-your-certificates). The Subject mapping functionality described on this page makes it possible to use CAs that do not place restrictions on the `CommonName` field but do place restrictions on other subject fields (for example, that every cert has an `OU` field based on the user that created it). The [default workflow using `cockroach cert`](/docs/v26.4/cockroach-cert#examples) only sets the `CommonName` field in its certificates, so the functionality described in this page is unnecessary. It is not possible to share a single CA managed by `cockroach cert` across multiple CockroachDB clusters. ## Example This example shows how to set up a mapping between the Subject field of an [X.509 certificate](https://en.wikipedia.org/wiki/X.509) and a SQL [user or role](/docs/v26.4/security-reference/authorization#roles). ### Step 1. Create certificates using your infrastructure These instructions assume that you have already created certificates using your own infrastructure for the following users: * The [`root` user](/docs/v26.4/security-reference/authorization). * The [`node` user](/docs/v26.4/security-reference/authorization). * Any [SQL user](/docs/v26.4/security-reference/authorization#sql-users) who needs to authenticate with your cluster. In this example, we will call the user `maxroach`. General guidelines for certificate creation: * The cluster name and SQL user name will generally both appear somewhere in the certificate's Subject. * The cluster name will usually go in the `OU` or `DC` fields, and the user name in `UID` or `CN` fields. You can also map the user name to a `SAN` field by enabling [Subject Alternative Name mapping](#optional-enable-the-cluster-setting-to-map-users-to-subject-alternative-name-san-fields). * For example, the Subject might look like `O=Acme Inc,OU=movr-prod,UID=root`. ### Step 2. Start your cluster with root and node certificate flags At cluster startup, you'll need to pass the [`cockroach start`](/docs/v26.4/cockroach-start) flags [`--node-cert-distinguished-name`](/docs/v26.4/cockroach-start) and [`--root-cert-distinguished-name`](/docs/v26.4/cockroach-start). The argument to each flag is a string with a comma separated list of distinguished name (DN) mappings in `{attribute-type}={attribute-value}` format in accordance with [RFC4514](https://www.rfc-editor.org/rfc/rfc4514). When each of these flags are set, the argument needs to be an exact match with the DN subject in the client certificate provided. By exact match, we mean that the order of attributes in the argument must match the order of attributes in the DN subject in the certificate. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach start --certs-dir=/path/to/certs --node-cert-distinguished-name="O=Acme Inc,OU=movr-prod,UID=node" --root-cert-distinguished-name="O=Acme Inc,OU=movr-prod,UID=root" # other startup flags, etc. ``` The DN mappings in the certificates you create should match what you pass in at cluster start time. One way to create a certificate matching the `node` user in the example above is: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} openssl req -new -key /path/to/certs/client.node.key -out client.node.csr -batch -subj '/O=Acme Inc/OU=movr-prod/UID=node' ``` A similar command can be used to generate a certificate for the `root` user. If you plan to [map users to Subject Alternative Name (`SAN`) fields](#optional-enable-the-cluster-setting-to-map-users-to-subject-alternative-name-san-fields), also pass the [`--root-cert-san`](/docs/v26.4/cockroach-start#flags-root-cert-san) and [`--node-cert-san`](/docs/v26.4/cockroach-start#flags-node-cert-san) flags. Each flag takes a comma-separated list of `{attribute-type}={attribute-value}` `SAN` entries, where the attribute type is `DNS`, `IP`, or `URI`. These flags are enforced only when the `security.client_cert.san_required.enabled` cluster setting is `true`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach start --certs-dir=/path/to/certs --node-cert-san="DNS=node.movr-prod.example.com" --root-cert-san="DNS=root.movr-prod.example.com" # other startup flags, etc. ``` ### Step 3. Set the `SUBJECT` role option using `CREATE ROLE` or `ALTER ROLE` to match your certificates You can associate an [X.509](https://en.wikipedia.org/wiki/X.509) certificate's Subject with a [role](/docs/v26.4/security-reference/authorization#roles) as shown below. Note that the Subject fields in the certificate have to be an exact match with what you pass in via the SQL statement. By exact match, we mean that the order of attributes passed in via the SQL statement must match the order of attributes in the certificate. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE maxroach WITH SUBJECT 'CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry' LOGIN; ``` Alternatively, you can update existing users with [`ALTER ROLE ... SUBJECT`](/docs/v26.4/alter-role#set-the-subject-role-option-for-certificate-based-authentication). ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER ROLE maxroach WITH SUBJECT 'CN=myName2,OU=myOrgUnit2,O=myOrg2,L=myLocality2,ST=myState2,C=myCountry2' LOGIN; ``` Note that `ALTER ROLE ... SUBJECT` cannot be applied to the `root` user. You must use `cockroach start --root-cert-distinguished-name` instead. ``` ERROR: role "root" cannot have a SUBJECT%!(EXTRA string=use the --%s CLI flag to configure root, string=root-cert-distinguished-name) SQLSTATE: 22023 ``` If you do not have an [enterprise license](/docs/v26.4/licensing-faqs), the following error is signaled: ``` ERROR: use of SUBJECT role option requires an enterprise license. see https://cockroachlabs.com/pricing for details on how to enable enterprise features SQLSTATE: XXC02 ``` ### Step 4. Enable the cluster setting to require the Subject field in certificates Once the cluster is started, enable the following [cluster setting](/docs/v26.4/cluster-settings#setting-security-client-cert-subject-required-enabled): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING security.client_cert.subject_required.enabled = true; ``` When this setting is enabled, users who don't have a `SUBJECT` role option set will be unable to log in with certificates. Regardless of this setting's value, CockroachDB will verify the following during user authentication provided the Subject options or DN flags or both are set: * For the `root` user, that the distinguished name in the certificate Subject matches the distinguished name fields passed in via `cockroach start --root-cert-distinguished-name`. * For the `node` user, that the distinguished name in the certificate Subject matches the distinguished name fields passed in via `cockroach start --node-cert-distinguished-name`. * For all other SQL users, that the values in the Subject field of the [X.509 certificate](https://en.wikipedia.org/wiki/X.509) match the values attached to the user or role with `CREATE ROLE ... SUBJECT` or `ALTER ROLE ... SUBJECT`. #### (Optional) Enable the cluster setting to map users to Subject Alternative Name (`SAN`) fields If your organization uses Subject Alternative Name (`SAN`) fields for user identity mapping, enable the following cluster setting to authenticate client certificates by their `SAN` entries instead of the default `CN` lookup: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING security.client_cert.san_required.enabled = true; ``` When this setting is enabled, every client certificate must contain at least one `SAN` entry, and CockroachDB establishes the identity of each user as follows: * For the `root` user, every `SAN` entry passed to [`cockroach start --root-cert-san`](/docs/v26.4/cockroach-start#flags-root-cert-san) must be present in the certificate's `SAN` entries. If `--root-cert-san` is not set, `root` certificate login is rejected unless [`--root-cert-distinguished-name`](/docs/v26.4/cockroach-start#flags-root-cert-distinguished-name) is set and matches the certificate's Subject DN. Enabling this setting without one of these flags locks `root` out of certificate authentication. * For the `node` user, every `SAN` entry passed to [`cockroach start --node-cert-san`](/docs/v26.4/cockroach-start#flags-node-cert-san) must be present in the certificate's `SAN` entries. If `--node-cert-san` is not set, `node` certificate login is rejected unless [`--node-cert-distinguished-name`](/docs/v26.4/cockroach-start#flags-node-cert-distinguished-name) is set and matches the certificate's Subject DN. * For `debug_user`, the certificate must be issued for `debug_user`. Refer to [Using debug_user for diagnostics](/docs/v26.4/security-reference/authentication#using-debug_user-for-diagnostics). * For all other SQL users, the certificate must be explicitly bound to the SQL user by **one** of the following: * An **identity map**: a `map` option on the certificate rule in the [HBA configuration](/docs/v26.4/security-reference/authentication#hba-configuration-syntax), together with a matching line in the `server.identity_map.configuration` cluster setting. See [Bind a SAN to a SQL user with an identity map](#bind-a-san-to-a-sql-user-with-an-identity-map). * An **exact subject DN**: the `SUBJECT` role option set to the certificate's full Subject DN, as described in [Step 3](#step-3-set-the-subject-role-option-using-create-role-or-alter-role-to-match-your-certificates). The certificate's `CN` is **not** used as a fallback. A non-privileged SQL user whose certificate is bound by neither an identity map nor a `SUBJECT` DN is rejected with an error such as: ``` ERROR: certificate authentication failed for user "maxroach": SAN-based authentication requires an identity map ``` > [!WARNING] > > Before you enable `security.client_cert.san_required.enabled`, and before you upgrade a cluster that already has it enabled to v26.4, make sure that: > > * Every node is started with `--root-cert-san` and `--node-cert-san`, or with `--root-cert-distinguished-name` and `--node-cert-distinguished-name`, so that the `root` and `node` certificates continue to be accepted. > * Every non-privileged SQL user who authenticates with a client certificate is bound to that certificate by an identity map or a `SUBJECT` DN. Previously, CockroachDB could accept such a certificate without verifying the binding. In v26.4 and later (and in the v26.3.2 and v26.2.7 patch releases), those logins are rejected. The `auth.cert.san.conn.total` and `auth.cert.san.conn.success` [metrics](/docs/v26.4/metrics) track the number of SQL connection attempts, and successful connections, that use `SAN`-based certificate authentication. ##### Bind a SAN to a SQL user with an identity map The identity map follows the PostgreSQL [`pg_ident.conf` user name map](https://www.postgresql.org/docs/current/auth-username-maps.html) format: each line of `server.identity_map.configuration` is a space-separated triple of map name, external identity, and SQL username, and the map name is the value you reference with the `map` option in the HBA configuration. For `SAN`-based certificate authentication, the external identity has the format `SAN:{attribute-type}:{attribute-value}`, where the attribute type is `DNS`, `URI`, or `IP`. For example: `SAN:DNS:maxroach.example.com`, `SAN:URI:spiffe://example.org/maxroach`, or `SAN:IP:10.0.0.5`. A literal external identity matches case-insensitively. An external identity that starts with `/` is treated as a regular expression, and the SQL username can reference its first capture group as `\1`. > [!NOTE] > > This is not the same format as the [SSO identity map](/docs/v26.4/sso-sql#identity-map-configuration) used for JWT authentication, where the first field is the token issuer URL rather than a map name. The following example binds a client certificate with a `DNS` `SAN` entry to the SQL user `maxroach`. 1. Create a client certificate for `maxroach` that carries a `SAN` entry. For example, using `openssl`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} openssl req -new -key /path/to/certs/client.maxroach.key -out client.maxroach.csr -batch -subj '/O=Acme Inc/OU=movr-prod/CN=maxroach' -addext 'subjectAltName=DNS:maxroach.example.com' ``` 2. Add a line to the identity map that maps the `SAN` entry to the SQL user. This example names the map `crdb`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.identity_map.configuration = 'crdb SAN:DNS:maxroach.example.com maxroach'; ``` 3. Reference the map from the certificate rule in the HBA configuration with the `map` option. The `cert`, `cert-password`, and `cert-scram-sha-256` methods all accept `map`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.host_based_authentication.configuration = 'host all all all cert map=crdb'; ``` A client that presents the `maxroach` certificate can now connect as `maxroach`. If the certificate's `SAN` entries do not match any line in the map, or map to a different SQL user than the one requested in the connection, the connection is rejected. ## See also * [`ALTER ROLE ... SUBJECT`](/docs/v26.4/alter-role#set-the-subject-role-option-for-certificate-based-authentication) * [`CREATE ROLE ... SUBJECT`](/docs/v26.4/create-role#set-the-subject-role-option-for-certificate-based-authentication) * [Authenticate to CockroachDB self-hosted Clusters](/docs/v26.4/authentication) * [GSSAPI Authentication](/docs/v26.4/gssapi_authentication) * [SQL Authentication](/docs/v26.4/security-reference/authentication) * [Cloud Storage Authentication](/docs/v26.4/cloud-storage-authentication) * [Cluster Settings](/docs/v26.4/cluster-settings#setting-security-client-cert-subject-required-enabled) * [`cockroach start`](/docs/v26.4/cockroach-start) * [`cockroach cert`](/docs/v26.4/cockroach-cert) * [`cockroach auth-session`](/docs/v26.4/cockroach-auth-session) # CockroachDB Plugins for AI Tools Source: https://docs.cockroachlabs.com/docs/stable/cockroachdb-ai-plugins CockroachDB provides official plugins for [Claude Code](https://code.claude.com/), [Cursor](https://cursor.com/), and [OpenAI Codex](https://developers.openai.com/codex/). The plugins connect your AI coding tools of choice directly to your CockroachDB clusters for exploring schemas, writing optimized SQL, debugging queries, and managing clusters. Each plugin provides tools across MCP backends (self-hosted MCP Toolbox and the managed [CockroachDB Cloud MCP Server](/docs/v26.4/cockroachdb-mcp-server)), skills across operational domains, and built-in safety protections, and the Claude Code and Cursor plugins also include specialized agents. The official CockroachDB AI plugins come with the following components: * **MCP backends**: `cockroachdb-toolbox` for any cluster through MCP Toolbox, and `cockroachdb-cloud` for the managed [CockroachDB Cloud MCP Server](/docs/v26.4/cockroachdb-mcp-server). Additional backends, including the [CockroachDB MCP Server](/docs/v26.4/cockroachdb-mcp-server) for self-hosted clusters, can be added manually. * **Cluster management tools**: the [`ccloud` CLI](/docs/cockroachcloud/ccloud-get-started) for cluster lifecycle, backups, disaster recovery, networking, and audit tasks, which agents call directly through the shell. * **SQL client tools**: list schemas and tables, inspect cluster and database details, and run SQL. SQL through MCP Toolbox is read-only unless write mode is enabled; the Cloud MCP Server provides separate write tools governed by your CockroachDB Cloud permissions. * **Agents and skills**: skills across operational domains in every plugin, plus specialized DBA, Developer, and Operator agents in the Claude Code and Cursor plugins. * **Safety protections**: In the Claude Code and Codex plugins, built-in safety hooks block dangerous statements. In the Cursor plugin, safety and best-practice rules steer the model away from risky behavior. ## Prerequisites The official CockroachDB plugins come bundled with the following MCP servers, which have their own requirements: * The `cockroachdb-toolbox` server works with any self-hosted or Cloud cluster. It requires [MCP Toolbox for Databases](https://github.com/googleapis/mcp-toolbox) v1.0.0 or later on your `PATH`, and a running CockroachDB cluster it can reach. On macOS or Linux, install Toolbox with `brew install mcp-toolbox`. For Windows and other platforms, refer to the plugin repository's installation instructions. * The `cockroachdb-cloud` server requires a [CockroachDB Cloud](https://cockroachlabs.cloud/) account. There is no local server to set up, but the server requires OAuth sign-in to CockroachDB Cloud in every tool. In Claude Code, run `/mcp` and select the server to sign in. In Cursor, the server signs in with OAuth through your browser. In Codex, no configuration is needed beyond the OAuth sign-in, and the server can reach the clusters that your CockroachDB Cloud role allows. ## Install the Claude Code plugin Install the [CockroachDB plugin from the Claude marketplace](https://claude.com/marketplace/plugins/cockroachdb), or run the following in Claude Code: ``` /plugin install cockroachdb@claude-plugins-official ``` To install from the plugin repository's own marketplace instead: ``` /plugin marketplace add cockroachdb/claude-plugin /plugin install cockroachdb@cockroachdb-claude-plugin ``` ## Install the Cursor plugin Install the [CockroachDB plugin from the Cursor marketplace](https://cursor.com/marketplace/cockroachdb), or run the following in Cursor: ``` /add-plugin cockroachdb ``` ## Install the Codex plugin The CockroachDB plugin for the [OpenAI Codex CLI](https://developers.openai.com/codex/cli/install) is listed on the [ChatGPT and Codex plugin listing](https://chatgpt.com/plugins/plugin_asdk_app_6ae160c3d9e48191aaeffd03cc5ef09d). To install, add the plugin marketplace and the plugin: ``` codex plugin marketplace add cockroachdb/codex-plugin codex plugin add cockroachdb@cockroachdb-codex-plugin ``` Codex skips plugin hooks until you review and trust them. Run `/hooks` in a Codex session and trust the two CockroachDB safety hooks. ## See also * [CockroachDB and AI](/docs/v26.4/cockroachdb-and-ai) * [CockroachDB MCP Server](/docs/v26.4/cockroachdb-mcp-server) * [Agent Skills](/docs/v26.4/agent-skills) * [claude-plugin](https://github.com/cockroachdb/claude-plugin) * [cursor-plugin](https://github.com/cockroachdb/cursor-plugin) * [codex-plugin](https://github.com/cockroachdb/codex-plugin). # CockroachDB and AI Source: https://docs.cockroachlabs.com/docs/stable/cockroachdb-and-ai CockroachDB supports AI in two primary ways: as a platform that enables AI-assisted development and administration, and as a data store for AI applications. **Support for AI-assisted workflows**: CockroachDB integrates with AI development tools, including Claude Code, Cursor, and GitHub Copilot in VS Code. [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) servers provide access to CockroachDB clusters and CockroachDB documentation. The Agent Skills repository encodes operational workflows in a machine-executable format. For more information, refer to [Support for AI-assisted workflows](#support-for-ai-assisted-workflows). **A data store for AI applications**: CockroachDB can serve as the system of record and the retrieval engine for AI applications. It combines native support for vector data and similarity search with strongly consistent transactions, horizontal scalability, and multi-region deployments. These capabilities support storing vector embeddings, agent state, conversation histories, and other AI-related data alongside relational data. For more information, refer to [CockroachDB as a data store for AI applications](#cockroachdb-as-a-data-store-for-ai-applications). ## Support for AI-assisted workflows CockroachDB enables your AI development tools to work directly with CockroachDB and CockroachDB Cloud. CockroachDB provides the following functionality to support AI-assisted deployment and maintenance of clusters, and AI-assisted development of applications: * Official plugins for Claude Code, Cursor, and OpenAI Codex, described in [CockroachDB AI Plugins](/docs/v26.4/cockroachdb-ai-plugins). * Cluster-level read and write access via the [CockroachDB Cloud MCP server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server). * Cluster-level read and write access for self-hosted deployments via the [CockroachDB MCP Server](/docs/v26.4/cockroachdb-mcp-server). * Operational workflows encoded as [Agent Skills for CockroachDB](/docs/v26.4/agent-skills). * Command-line automation with the [`ccloud` CLI](/docs/cockroachcloud/ccloud-get-started), designed to be compatible with AI agents. * Access to the Cockroach Labs public documentation via the [CockroachDB Docs MCP server](/docs/v26.4/docs-mcp-integration). The following sections provide an overview of these tools. ### CockroachDB AI plugins Official CockroachDB plugins for Claude Code, Cursor, and OpenAI Codex bundle many of the capabilities described in this section, including MCP backends for connecting to your clusters, skills across operational domains, and built-in safety protections. The Claude Code and Cursor plugins also provide specialized agents for interacting with CockroachDB. Installing a plugin configures these integrations for your AI coding tool in one step. For what each plugin includes and how to install one, refer to [CockroachDB AI Plugins](/docs/v26.4/cockroachdb-ai-plugins). ### CockroachDB MCP servers CockroachDB provides Model Context Protocol (MCP) servers that expose a set of tools for inspecting and querying your clusters from your AI tools. These tools let your AI assistants list [databases](/docs/v26.4/show-databases) and [tables](/docs/v26.4/show-tables), describe [schemas](/docs/v26.4/show-schemas) and [indexes](/docs/v26.4/show-index), inspect cluster health and running queries, and run read-only SQL and [`EXPLAIN`](/docs/v26.4/explain) statements. When explicitly enabled, they can also [create databases](/docs/v26.4/create-database), [create tables](/docs/v26.4/create-table), and [insert rows](/docs/v26.4/insert). This allows you to manage and modify a CockroachDB cluster using natural language prompts. For example, you could use the following prompt to instruct your AI tool to interface with the cluster: ``` List all of the tables in the demo_db database. ``` An MCP server is available for both deployment types: CockroachDB Cloud clusters use the managed [CockroachDB Cloud MCP server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server), and self-hosted clusters use the [CockroachDB MCP Server](/docs/v26.4/cockroachdb-mcp-server), which you run yourself. ### Agent Skills for CockroachDB [Agent Skills for CockroachDB](/docs/v26.4/agent-skills) are small, structured capabilities that encode CockroachDB operational expertise in a machine-executable format. These skills live in the public [cockroachdb-skills](https://github.com/cockroachlabs/cockroachdb-skills) repository and follow the [Agent Skills Specification](https://agentskills.io/specification), with defined inputs, outputs, and safety guardrails. Each skill focuses on a specific task, such as auditing user privileges, triaging live SQL activity, validating production readiness, or checking backup and disaster recovery posture. Skills are organized into domains like onboarding and migrations, application development, performance and scaling, operations and lifecycle, resilience and disaster recovery, observability and diagnostics, security and governance, integrations, and cost management. Your AI tools can consume these skills directly, so you can reuse the same operational workflows across different toolchains. ### `ccloud` command-line interface The [`ccloud` CLI](/docs/cockroachcloud/ccloud-get-started) is the command-line interface for CockroachDB Cloud. You can use the `ccloud` CLI to create clusters, manage networking (for example, IP allowlists), create SQL users, retrieve connection information, and more. Because `ccloud` is text-based and follows a stable command structure, it is well-suited for AI tools and automations. An AI assistant can generate or run `ccloud` commands to set up clusters, rotate credentials, or retrieve connection URLs, while you keep access mediated through the CLI and existing Cloud authentication. ### CockroachDB Docs MCP server The [CockroachDB Docs MCP server](/docs/v26.4/docs-mcp-integration) exposes the published CockroachDB documentation to your MCP-compatible tools over HTTP. After you add the server configuration to your client, your AI assistant can answer questions using the official documentation without leaving your editor. For example, you could use your AI tool to ask the following: ``` How do table statistics get refreshed in CockroachDB? ``` An AI tool using the documentation MCP server can provide a response to this prompt informed by documentation pages such as [Cost-Based Optimizer](/docs/v26.4/cost-based-optimizer) and [`CREATE STATISTICS`](/docs/v26.4/create-statistics). This integration only provides access to CockroachDB product documentation. It does not connect to your clusters or data. It is intended to give your AI tools reliable product information while you develop and operate CockroachDB and CockroachDB Cloud. ## CockroachDB as a data store for AI applications CockroachDB provides the database features needed to store and query AI-related data, including vector embeddings and agent state, with the same transactional guarantees as your other workloads. ### Vector search and RAG AI applications often represent text, images, and other content as vector embeddings. These are numerical representations that capture semantic meaning. To find relevant information, AI applications need to search for vectors that are similar to a query vector, typically using distance metrics. This similarity search is fundamental to retrieval-augmented generation (RAG), semantic search, and recommendation systems. CockroachDB has a [`VECTOR` data type](/docs/v26.4/vector) for storing fixed-length floating-point embeddings and supports similarity operators such as L2 distance (`<->`), inner product (`<#>`), and cosine distance (`<=>`). You can index vectors using [`CREATE VECTOR INDEX`](/docs/v26.4/create-index#create-vector-indexes) and combine them with other indexed columns. You can store vector embeddings, relational data, and [JSON](/docs/v26.4/jsonb) metadata in the same table and query them together. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT id, name FROM items WHERE customer_id = 1 ORDER BY embedding <-> $query_vector LIMIT 5; ``` RAG systems depend on fast and accurate retrieval of contextual data. CockroachDB's vector support enables you to implement RAG and semantic search patterns so that you can use CockroachDB as the data store for AI applications. [Vector indexes](/docs/v26.4/vector-indexes) enable efficient similarity searches over large datasets. You can store document embeddings in a cluster alongside the source documents, metadata, and access control information associated with those documents. When a user query comes in, you can use vector similarity operators to retrieve semantically relevant documents, filter by permissions, and return both the relevant context and any associated metadata in a single transaction. See the [RAG tutorial](https://www.cockroachlabs.com/blog/tutorial-rag-with-cockroachdb/) for a complete implementation example. ### AI agent state and workflow coordination AI agents that perform autonomous operations require durable storage for execution state, workflow metadata, and operational history. These agents must track state transitions across multi-step processes, coordinate activities between concurrent executions, and ensure that operations can be safely retried or resumed after failures. CockroachDB's [transactional model](/docs/v26.4/transactions) provides a foundation for storing agent state, execution history, and coordination metadata. [Serializable isolation](/docs/v26.4/demo-serializable) ensures that state transitions occur correctly even when multiple agents or processes attempt concurrent updates. The database's [high availability](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures) design allows agents to continue operating during node or region failures without requiring external coordination services. ### Scale, consistency, and governance AI applications typically generate high data volumes, serve globally distributed users, and require both transactional correctness and operational durability. Conversation histories, vector embeddings, feature tables, and agent state accumulate quickly and are accessed across regions. These characteristics make AI workloads well-suited to CockroachDB's core design: * CockroachDB scales horizontally by adding nodes to increase capacity. * Data is automatically replicated and rebalanced across the cluster, so node failures do not require application-level failover. * [Multi-region deployments](/docs/v26.4/multiregion-overview) place data closer to users and can enforce [data locality](/docs/v26.4/regional-tables) or residency requirements while maintaining strong consistency. CockroachDB provides [serializable transactions](/docs/v26.4/demo-serializable) by default. Vector indexes participate in the same transaction and index maintenance model as other [secondary indexes](/docs/v26.4/indexes), so similarity search results remain aligned with the underlying data. This applies to tables storing embeddings, relational records, and agent state. ## See also * [Tutorial: Augment your AI use case with RAG on CockroachDB](https://www.cockroachlabs.com/blog/tutorial-rag-with-cockroachdb/) * [Real-Time Indexing for Billions of Vectors](https://www.cockroachlabs.com/blog/cspann-real-time-indexing-billions-vectors/) * [How CockroachDB's AI Assistance Boosts Developer Productivity](https://www.cockroachlabs.com/blog/cockroachdb-ai-assistance-for-developers/) * [Agent Development with CockroachDB using the LangChain Framework](https://www.cockroachlabs.com/blog/agent-development-cockroachdb-langchain/) * [CockroachDB AI Plugins](/docs/v26.4/cockroachdb-ai-plugins) (Claude Code, Cursor, and OpenAI Codex) * [Zero to AI Hero](https://youtu.be/PQdeDj9QSaU) * [Fraud Detection via Agentic AI](https://youtu.be/YzIv9yd5l_M) * [Vector Deep Dive](https://youtu.be/rR2G35NHdZQ) # CockroachDB MCP Server Source: https://docs.cockroachlabs.com/docs/stable/cockroachdb-mcp-server The CockroachDB MCP Server is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server that lets your AI coding tools and AI agents explore live schemas, run queries, and write data on a CockroachDB cluster. The server runs as a local subprocess or a shared HTTP service and exposes a set of typed tools that agents invoke on your behalf. Once connected, you can interact with your cluster using natural language prompts to perform operations such as listing tables, executing [`SELECT`](/docs/stable/select-clause) statements, and inserting rows. This page explains how the CockroachDB MCP Server works, and what functionality it enables. To learn how to set it up, refer to [Install, Configure, and Connect to the CockroachDB MCP Server](/docs/stable/install-cockroachdb-mcp-server). For the full list of configuration options, refer to the [CockroachDB MCP Server Reference](/docs/stable/cockroachdb-mcp-server-reference). For CockroachDB Cloud deployments, refer to [Connect to the CockroachDB Cloud MCP Server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server). ## Requirements * An existing [CockroachDB cluster](/docs/stable/install-cockroachdb-mac) with a [SQL user](/docs/stable/create-user) whose [privileges](/docs/stable/grant) are suitable for the operations that you want your AI agents to perform. * Installing with `go install` or building from source requires [Go 1.26 or later](https://go.dev/dl/). Alternatively, you can install with pre-built binaries (for Linux and Windows), and a Docker image is also available. ## How it works The server registers a set of [typed MCP tools](#tools) that AI agents invoke on your behalf. These tools trigger SQL queries against the connected cluster using a [CockroachDB SQL user](/docs/stable/create-user). The server supports two transports: * **stdio (default)**: Your AI tool launches the server as a local subprocess and communicates with it over standard input/output. Each user runs their own server instance, authenticated to the cluster with their own SQL credentials. This is the simplest deployment and the recommended starting point. * **HTTP**: The server runs as a long-lived process that multiple MCP clients connect to over HTTPS with a bearer token. This is best for shared or remote deployments. ## Security The server is configured with secure defaults and requires explicit opt-in to relax them. * **Read-only by default.** Unless you explicitly enable write tools with the [`CRDB_MCP_ENABLE_WRITE_QUERIES`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-enable-write-queries) environment variable, only read tools are registered, and every SQL session is additionally forced read-only with `default_transaction_read_only=true`. For per-operation control, grant the connecting SQL role only the privileges you want: for example, `SELECT`, `INSERT`, and `UPDATE` but not `DELETE` to allow writes without deletes. * **SQL grants are the permission boundary.** Security ultimately comes from what the connecting SQL user is allowed to do in CockroachDB (via [`GRANT`](/docs/stable/grant)), not from which environment variables you set on the MCP server. The server configuration controls which tools are registered, but even with write tools enabled, the SQL user can only do what its grants allow. Least-privilege grants are also the containment for prompt injection: the server cannot distinguish a tool call you intended from one induced by malicious content that the agent has read. * **Password authentication is rejected by default.** In stdio mode the server runs as a subprocess of the AI agent host, which can read passwords from the process environment or `~/.pgpass`. Certificate-based authentication is recommended; password-based authentication requires an explicit opt-in. * **TLS by default, in both directions.** Connections to the cluster require `sslmode` of `require` or stronger, and HTTP mode refuses to start without a TLS certificate and key. Running without TLS—for local development or behind a TLS-terminating reverse proxy—requires explicit opt-in. * **Background quality of service.** By default, queries run at `default_transaction_quality_of_service=background`, so agent traffic does not contend with latency-sensitive foreground workloads. ## Tools For the full tool specifications including parameters, refer to the [CockroachDB MCP Server Reference](/docs/stable/cockroachdb-mcp-server-reference). The server registers the following read-only tools by default: | Tool | Description | | - | - | | [`list_databases`](/docs/stable/cockroachdb-mcp-server-reference#list_databases) | List all databases in the cluster. | | [`list_tables`](/docs/stable/cockroachdb-mcp-server-reference#list_tables) | List all tables in a database. | | [`get_table_schema`](/docs/stable/cockroachdb-mcp-server-reference#get_table_schema) | Get the schema for a table, including columns and indexes. | | [`get_cluster`](/docs/stable/cockroachdb-mcp-server-reference#get_cluster) | Return cluster identity and version metadata. | | [`list_sql_users`](/docs/stable/cockroachdb-mcp-server-reference#list_sql_users) | List SQL users defined in the cluster. | | [`list_cluster_nodes`](/docs/stable/cockroachdb-mcp-server-reference#list_cluster_nodes) | List cluster nodes with address, liveness, and locality. | | [`show_running_queries`](/docs/stable/cockroachdb-mcp-server-reference#show_running_queries) | List in-flight SQL statements on the cluster. | | [`select_query`](/docs/stable/cockroachdb-mcp-server-reference#select_query) | Execute a [`SELECT`](/docs/stable/select-clause) statement. | | [`explain_query`](/docs/stable/cockroachdb-mcp-server-reference#explain_query) | Return the [`EXPLAIN`](/docs/stable/explain) plan for a statement without executing it. | | [`show_statement`](/docs/stable/cockroachdb-mcp-server-reference#show_statement) | Execute a `SHOW` statement such as `SHOW SCHEMAS`, `SHOW INDEXES`, or `SHOW JOBS`. | The following write tools are registered only when [`CRDB_MCP_ENABLE_WRITE_QUERIES`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-enable-write-queries)`=true` is set: | Tool | Description | | - | - | | [`create_database`](/docs/stable/cockroachdb-mcp-server-reference#create_database) | Create a database. | | [`create_table`](/docs/stable/cockroachdb-mcp-server-reference#create_table) | Execute a [`CREATE TABLE`](/docs/stable/create-table) statement. | | [`insert_rows`](/docs/stable/cockroachdb-mcp-server-reference#insert_rows) | Execute an [`INSERT`](/docs/stable/insert) statement. | | [`update_rows`](/docs/stable/cockroachdb-mcp-server-reference#update_rows) | Execute an [`UPDATE`](/docs/stable/update) statement. A `WHERE` clause is mandatory. | | [`delete_rows`](/docs/stable/cockroachdb-mcp-server-reference#delete_rows) | Execute a [`DELETE`](/docs/stable/delete) statement. A `WHERE` clause is mandatory. | ## Example usage Use natural language prompts to read from and write to the cluster. You likely do not have to invoke the preceding tools explicitly. Most AI tools should be able to decide which functions to call based on natural language prompts provided by the user. Prompts can be simple, for example: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} List all of the tables in the movr database. ``` They can also be complex and conversational, for example: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} I need to add a reviews table to the movr database so that riders can rate their rides. For the schema, I'm thinking we need: - Review ID (primary key) - Rider reference (foreign key to movr.users) - Ride reference (foreign key to movr.rides) - A 1–5 star rating - Optional text feedback - Timestamp Let's include a secondary index on the rating column. Show me the CREATE TABLE statement so that we can talk it through before you actually create the table. ``` ## See also * [Install, Configure, and Connect to the CockroachDB MCP Server](/docs/stable/install-cockroachdb-mcp-server) * [CockroachDB MCP Server Reference](/docs/stable/cockroachdb-mcp-server-reference) * [Connect to the CockroachDB Cloud MCP Server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server) * [CockroachDB and AI](/docs/stable/cockroachdb-and-ai) * [Agent Skills for CockroachDB](/docs/stable/agent-skills) * [Docs MCP Server](/docs/stable/docs-mcp-integration) # CockroachDB MCP Server Reference Source: https://docs.cockroachlabs.com/docs/stable/cockroachdb-mcp-server-reference This page lists the configuration options for the [MCP Server](/docs/stable/cockroachdb-mcp-server) that connects to self-hosted CockroachDB deployments. To set up the server, refer to [Install, Configure, and Connect to the CockroachDB MCP Server](/docs/stable/install-cockroachdb-mcp-server). ## Configuration All configuration is managed via environment variables. In stdio mode, set them in the `env` block of your MCP client configuration; in HTTP mode, export them in the server's environment. ### Authentication Certificate-based authentication is recommended in stdio mode. The server runs as a subprocess of the AI agent host, which can read `CRDB_PWD`, a password embedded in `CRDB_DATABASE_URL`, `PGPASSWORD`, or `~/.pgpass` from the process's environment. To protect those credentials, password-based authentication is rejected by default; set [`CRDB_MCP_ALLOW_PASSWORD_AUTH`](#crdb-mcp-allow-password-auth)`=true` to opt in. You can authenticate with individual variables (recommended) or with a full connection string. [`CRDB_DATABASE_URL`](#crdb-database-url) takes precedence when both are set. | Variable | Description | Required | Default | | - | - | - | - | | `CRDB_HOST` | Hostname. For a multi-node cluster, use a load balancer address; for development, any node's address. | Yes | | | `CRDB_PORT` | Port. | No | `26257` | | `CRDB_USERNAME` | SQL user. | Yes | | | `CRDB_PWD` | Password. Requires [`CRDB_MCP_ALLOW_PASSWORD_AUTH`](#crdb-mcp-allow-password-auth)`=true`. Certificate-based authentication is recommended instead. | No | | | `CRDB_SSL_MODE` | `require`, `verify-ca`, or `verify-full`. TLS-optional modes (`disable`, `allow`, `prefer`) require [`CRDB_MCP_ALLOW_INSECURE_DB`](#crdb-mcp-allow-insecure-db)`=true`. | No | `verify-full` | | `CRDB_SSL_CA_PATH` | CA certificate path. | When `CRDB_SSL_MODE` is `verify-ca` or `verify-full` (the default) | | | `CRDB_SSL_CERTFILE` | Client certificate path. | When `CRDB_SSL_MODE` is `require`, `verify-ca`, or `verify-full` (the default) | | | `CRDB_SSL_KEYFILE` | Client key path. | When `CRDB_SSL_MODE` is `require`, `verify-ca`, or `verify-full` (the default) | | Alternatively, use a full connection string: | Variable | Description | | - | - | | `CRDB_DATABASE_URL` | A full libpq connection string (for example, `postgresql://user@host:26257/defaultdb?sslmode=verify-full&sslcert=...`). When set, the individual variables above are ignored. A `CRDB_DATABASE_URL` that omits `sslmode` is rejected at startup. | ### Query behavior | Variable | Description | Required | Default | | - | - | - | - | | `CRDB_MCP_QUERY_TIMEOUT` | Per-query timeout, as a Go duration (for example, `30s`). The server cancels a query that exceeds it. | No | `30s` | | `CRDB_MCP_MAX_ROWS_COUNT` | Cap on the maximum `LIMIT` that list-style tools issue to CockroachDB. | No | `10000` | | `CRDB_MCP_MAX_CONNS` | Upper bound on the connection pool size (up to 100). | No | `10` | | `CRDB_MCP_TXN_QOS` | Default transaction quality of service: `background`, `regular`, or `critical`. Refer to the precedence notes below the table. | No | `background` | | `CRDB_MCP_ENABLE_WRITE_QUERIES` | Enable the [write tools](#write-tools). For per-operation control, grant the connecting role only the SQL privileges you want, for example `SELECT`, `INSERT`, and `UPDATE` but not `DELETE` to allow writes without deletes. | No | `false` | | `CRDB_MCP_ALLOW_PASSWORD_AUTH` | Opt in to password-based authentication. The server refuses to start if a password is detected from any source ([`CRDB_PWD`](#crdb-pwd), a password in [`CRDB_DATABASE_URL`](#crdb-database-url), `PGPASSWORD`, or `~/.pgpass`) unless this is set to `true`. | No | `false` | | `CRDB_MCP_ALLOW_INSECURE_DB` | Opt in to the `sslmode` values that can run without TLS: `disable`, `allow`, `prefer`. Certificate variables are not required in these modes. Development only. | No | `false` | MCP traffic runs at `default_transaction_quality_of_service=background` by default, so it does not contend with latency-sensitive foreground workloads. The value is chosen with the following precedence: 1. [`CRDB_MCP_TXN_QOS`](#crdb-mcp-txn-qos), if set (`background`, `regular`, or `critical`). 2. Otherwise, a `default_transaction_quality_of_service=...` query parameter in [`CRDB_DATABASE_URL`](#crdb-database-url), if present. 3. Otherwise, `background`. ### Transport | Variable | Description | Required | Default | | - | - | - | - | | `CRDB_MCP_TRANSPORT` | `stdio` or `http`. | No | `stdio` | | `CRDB_MCP_HTTP_LISTEN_ADDR` | Listen address in HTTP mode, any `host:port`. Omit the host to bind all interfaces. Examples: `:8080`, `0.0.0.0:8443`, `127.0.0.1:9090`. | No | `:8080` | | `CRDB_MCP_BEARER_TOKEN` | Bearer token that clients must send in `Authorization: Bearer {token}`. Must be at least 16 characters. | Required for `http` mode, unless [`CRDB_MCP_ALLOW_NO_BEARER`](#crdb-mcp-allow-no-bearer)`=true` | | | `CRDB_MCP_TLS_CERT` | PEM-encoded server certificate path. | Required for `http` mode, unless [`CRDB_MCP_ALLOW_INSECURE_HTTP`](#crdb-mcp-allow-insecure-http)`=true` | | | `CRDB_MCP_TLS_KEY` | PEM-encoded private key path. | Required for `http` mode, unless [`CRDB_MCP_ALLOW_INSECURE_HTTP`](#crdb-mcp-allow-insecure-http)`=true` | | | `CRDB_MCP_ALLOW_INSECURE_HTTP` | Opt in to cleartext HTTP (for reverse-proxy deployments). | No | `false` | | `CRDB_MCP_ALLOW_NO_BEARER` | Opt in to skipping bearer authentication (for upstream-auth deployments). A startup warning is logged. Mutually exclusive with [`CRDB_MCP_BEARER_TOKEN`](#crdb-mcp-bearer-token): the server refuses to start if both are set. | No | `false` | ### Logging | Variable | Description | Required | Default | | - | - | - | - | | `CRDB_MCP_LOG_LEVEL` | `debug`, `info`, `warn`, or `error`. | No | `info` | | `CRDB_MCP_LOG_PATH` | Log file path, or `-` for stderr. No rotation; use logrotate or your orchestrator. | No | | ### Tracing (OpenTelemetry) Tracing is opt-in. When neither of the following variables is set, no exporter is installed. When enabled, tool calls and their SQL statements are exported as spans, and server logs are exported as OpenTelemetry log records. Query text and errors are redacted before export, so literals and user data never leave the server. | Variable | Description | Required | | - | - | - | | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP gRPC endpoint; the standard `OTEL_*` environment variables are honored. | No | | `CRDB_MCP_OTEL_FILE` | Write traces and logs as JSON lines to this file instead (takes precedence). | No | ## Tools The following sections list the tools that the MCP server makes available to agents. You likely do not have to invoke these functions explicitly. Most AI tools should be able to decide which functions to call based on natural language prompts provided by the user. ### Read-only tools The following tools are registered by default. They do not modify cluster data. #### `list_databases` List all databases in the cluster. | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `limit` | Maximum rows to return, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). | integer | No | `100` | | `offset` | Rows to skip before returning results. | integer | No | `0` | #### `list_tables` List all tables in a database. | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `database` | Database whose tables are listed. | string | Yes | | | `limit` | Maximum rows to return, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). | integer | No | `100` | | `offset` | Rows to skip before returning results. | integer | No | `0` | #### `get_table_schema` Get detailed schema information for a table, including columns and indexes. Returns the [`CREATE TABLE`](/docs/stable/create-table) statement. | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `database` | Database containing the table. | string | Yes | | | `table` | Table name. | string | Yes | | | `schema` | Schema name. | string | No | `public` | #### `get_cluster` Return cluster identity and version metadata: `cluster_id`, `cluster_name`, `binary_version`, `active_version`. The identity fields (`cluster_id`, `cluster_name`, and `active_version`) require access to `crdb_internal` built-in functions, which are gated by default on CockroachDB v25.4 and later. When these fields cannot be accessed, they are returned as `null`, with the reason reported under an `unavailable` key. `binary_version` is always returned. This tool takes no parameters. #### `list_sql_users` List SQL users defined in the cluster. | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `limit` | Maximum rows to return, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). | integer | No | `100` | | `offset` | Rows to skip before returning results. | integer | No | `0` | #### `list_cluster_nodes` List cluster nodes with address, liveness, and locality. Requires `admin` or the `VIEWCLUSTERMETADATA` [system privilege](/docs/stable/security-reference/authorization#supported-privileges). This tool takes no parameters. #### `show_running_queries` List in-flight SQL statements on the cluster, ordered by start time descending. Viewing other users' statements requires `admin` or the `VIEWACTIVITY` or `VIEWACTIVITYREDACTED` [system privilege](/docs/stable/security-reference/authorization#supported-privileges); otherwise, only the connecting user's own statements are returned. | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `limit` | Maximum rows to return, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). | integer | No | `100` | | `offset` | Rows to skip before returning results. | integer | No | `0` | #### `select_query` Execute a single [`SELECT`](/docs/stable/select-clause) statement. Non-`SELECT` statements are rejected. A default `LIMIT` of `100` is appended when none is supplied, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). An explicit `LIMIT` that exceeds [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count), or `LIMIT ALL`, is rejected. | Parameter | Description | Type | Required | | - | - | - | - | | `query` | A single `SELECT` statement. | string | Yes | #### `explain_query` Return the [`EXPLAIN`](/docs/stable/explain) plan for a single SQL statement without executing it. `EXPLAIN ANALYZE` (and `EXPLAIN ANALYZE (DEBUG)`) is rejected because it executes the statement. Display options (`VERBOSE`, `DISTSQL`, `TYPES`, `OPT`, and so on) pass through. | Parameter | Description | Type | Required | | - | - | - | - | | `query` | A single SQL statement. | string | Yes | #### `show_statement` Execute a single `SHOW` statement such as `SHOW SCHEMAS`, `SHOW INDEXES`, `SHOW REGIONS`, or `SHOW JOBS`. A default `LIMIT` is appended, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `query` | A single `SHOW` statement. | string | Yes | | | `limit` | Maximum rows to return, capped at [`CRDB_MCP_MAX_ROWS_COUNT`](#crdb-mcp-max-rows-count). | integer | No | `100` | | `offset` | Rows to skip before returning results. | integer | No | `0` | ### Write tools The following tools are registered only when [`CRDB_MCP_ENABLE_WRITE_QUERIES`](#crdb-mcp-enable-write-queries)`=true` is set. Any write tool that includes a `RETURNING` clause returns the affected rows instead of just the count. #### `create_database` Create a database. | Parameter | Description | Type | Required | Default | | - | - | - | - | - | | `name` | Database name to create. | string | Yes | | | `if_not_exists` | When `true`, the statement is a no-op if the database already exists. | boolean | No | `false` | #### `create_table` Execute a single [`CREATE TABLE`](/docs/stable/create-table) statement. | Parameter | Description | Type | Required | | - | - | - | - | | `statement` | A single `CREATE TABLE` statement. Qualify the table with a database when not using the connection's default database. | string | Yes | #### `insert_rows` Execute a single [`INSERT`](/docs/stable/insert) statement. Returns the number of rows affected. | Parameter | Description | Type | Required | | - | - | - | - | | `statement` | A single `INSERT` statement. A `RETURNING` clause returns the inserted rows. Qualify the table with a database when not using the connection's default database. | string | Yes | #### `update_rows` Execute a single [`UPDATE`](/docs/stable/update) statement. A `WHERE` clause is mandatory. Returns the number of rows affected. | Parameter | Description | Type | Required | | - | - | - | - | | `statement` | A single `UPDATE` statement. A `WHERE` clause is mandatory. A `RETURNING` clause returns the updated rows. Qualify the table with a database when not using the connection's default database. | string | Yes | #### `delete_rows` Execute a single [`DELETE`](/docs/stable/delete) statement. A `WHERE` clause is mandatory. Returns the number of rows affected. | Parameter | Description | Type | Required | | - | - | - | - | | `statement` | A single `DELETE` statement. A `WHERE` clause is mandatory. A `RETURNING` clause returns the deleted rows. Qualify the table with a database when not using the connection's default database. | string | Yes | ## See also * [CockroachDB MCP Server](/docs/stable/cockroachdb-mcp-server) * [Install, Configure, and Connect to the CockroachDB MCP Server](/docs/stable/install-cockroachdb-mcp-server) * [CockroachDB MCP Server on GitHub](https://github.com/cockroachdb/cockroachdb-mcp-server) # CockroachDB Operator Overview Source: https://docs.cockroachlabs.com/docs/stable/cockroachdb-operator-overview The CockroachDB operator is a fully-featured [Kubernetes operator](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) that allows you to deploy and manage CockroachDB self-hosted clusters. The CockroachDB operator's source code is available in the [cockroachdb/cockroachdb-operator](https://github.com/cockroachdb/cockroachdb-operator) repository on GitHub. The operator is installed with the CockroachDB Helm charts as described in the [deployment guide](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator); building the operator from source is not currently supported. ## CockroachDB operator This section describes how to: * [Deploy a CockroachDB cluster using the CockroachDB operator](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator). * Migrate from an existing CockroachDB Kubernetes deployment using [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) or the [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator). * Operate a CockroachDB cluster: * [Manage pod scheduling](/docs/v26.4/schedule-cockroachdb-operator). * [Manage cluster resources](/docs/v26.4/configure-cockroachdb-operator). * [Manage certificates](/docs/v26.4/secure-cockroachdb-operator). * [Scale a cluster](/docs/v26.4/scale-cockroachdb-operator). * [Monitor a cluster](/docs/v26.4/monitor-cockroachdb-operator). * [Upgrade a cluster](/docs/v26.4/upgrade-cockroachdb-operator). * [Override deployment templates](/docs/v26.4/override-templates-cockroachdb-operator). * [Improve cluster performance](/docs/v26.4/cockroachdb-operator-performance). ## Kubernetes terminology Before starting, review some basic Kubernetes terminology. Note that CockroachDB [nodes](/docs/v26.4/architecture/glossary#cockroachdb-architecture-terms) are distinct from Kubernetes "nodes" or "worker nodes". | Feature | Description | | - | - | | [node](https://kubernetes.io/docs/concepts/architecture/nodes/) | A physical or virtual machine. In the [deployment guide](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator), you'll create instances and join them as worker nodes into a single Kubernetes cluster. | | [pod](http://kubernetes.io/docs/user-guide/pods/) | A pod is a group of one of more Docker containers. In the [deployment guide](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator), each pod will run on a separate Kubernetes worker node and include one Docker container running a single CockroachDB node, reflecting our [topology recommendations](/docs/v26.4/recommended-production-settings#topology). | | [operator](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) | An operator is an extension to Kubernetes that uses custom resources to efficiently manage specific applications. The CockroachDB operator includes two custom resource definitions to manage CockroachDB, `CrdbCluster` and `CrdbNode`. Unlike the older [Public operator](https://github.com/cockroachdb/cockroach-operator), the CockroachDB operator does not use StatefulSets and is designed to simplify multi-region deployments. | | [persistent volume](http://kubernetes.io/docs/user-guide/persistent-volumes/) | A persistent volume is a piece of networked storage (Persistent Disk on GCE, Elastic Block Store on AWS) mounted into a pod. The lifetime of a persistent volume is decoupled from the lifetime of the pod that's using it, ensuring that each CockroachDB node binds back to the same storage on restart. The [deployment guide](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator) assumes that dynamic volume provisioning is available. When that is not the case, [persistent volume claims](http://kubernetes.io/docs/user-guide/persistent-volumes/#persistentvolumeclaims) need to be created manually. | | [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) | RBAC, or Role-Based Access Control, is the system Kubernetes uses to manage permissions within the cluster. In order to take an action (e.g., `get` or `create`) on an API resource (e.g., a `pod`), the client must have a `Role` that allows it to do so. The [deployment guide](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator) creates the RBAC resources necessary for CockroachDB to create and access certificates. | # Performance with the CockroachDB Operator Source: https://docs.cockroachlabs.com/docs/stable/cockroachdb-operator-performance Kubernetes provides many useful abstractions for deploying and operating distributed systems, but some of the abstractions come with a performance overhead and an increase in underlying system complexity. This page outlines potential bottlenecks when running CockroachDB in Kubernetes and how to optimize performance. ## Before you begin Before you focus on optimizing a Kubernetes-orchestrated CockroachDB cluster: 1. Before deploying on Kubernetes, ensure that performance is optimized for your workload on identical hardware. You may find that you first need to [modify your workload](/docs/v26.4/performance-best-practices-overview) or use [different machine specs](/docs/v26.4/recommended-production-settings#hardware) to achieve the performance you need. 2. Read the documentation for [deploying CockroachDB on a Kubernetes cluster](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster) to familiarize yourself with the necessary Kubernetes terminology and deployment abstractions. ## Performance factors A number of independent factors affect performance when running CockroachDB on Kubernetes. Most are easiest to change before you create your CockroachDB cluster. If you need to modify a CockroachDB cluster that is already running on Kubernetes, extra care and testing is strongly recommended. The following sections show how to modify excerpts from the configuration YAML file. You can generate this file locally for modification with the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm show values cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} > values.yaml ``` ### Version of CockroachDB Because CockroachDB is under very active development, there are typically substantial performance gains in each release. If you are not experiencing optimal performance and aren't running the latest release, consider upgrading. ### Client workload Your workload is the single most important factor in database performance. Read through [SQL performance best practices](/docs/v26.4/performance-best-practices-overview) and determine whether you can make workload changes to speed up your application. ### Machine size The size of the machines you're using is not a Kubernetes-specific concern, but is a good place to start if you want more performance. Using machines with more CPU will almost always allow for greater throughput. Because Kubernetes runs a set of processes on every machine in a cluster, it is typically more efficient to use fewer large machines than more small machines. For specific suggestions, refer to [Hardware](/docs/v26.4/recommended-production-settings#hardware). ### Disk type CockroachDB makes heavy use of the disks you provide it, so using faster disks is an easy way to improve your cluster's performance. For the best performance, [SSDs are strongly recommended](/docs/v26.4/recommended-production-settings#hardware). The Cockroach Labs-provided configuration does not specify disk type, so in most environments Kubernetes will auto-provision disks of the default type. In the common cloud environments (AWS, GCP, Azure) this means you'll get slow disks that aren't optimized for database workloads (e.g., HDDs on GCE, SSDs without provisioned IOPS on AWS). #### Create a different disk type Kubernetes exposes the disk types used by its volume provisioner via its [`StorageClass` API object](https://kubernetes.io/docs/concepts/storage/storage-classes/). Each cloud environment has a default `StorageClass`, but you can easily change the default or create a new named class that you can specify later. To do this, pick a volume provisioner from the list in the [Kubernetes documentation](https://kubernetes.io/docs/concepts/storage/storage-classes/), modify the example YAML file to specify the disk type you want, then run `kubectl create -f {your-storage-class-file}.yaml`. For example, in order to use the `pd-ssd` disk type on Google Compute Engine or Google Kubernetes Engine, you can use a `StorageClass` file like the following: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: {your-ssd-class-name} provisioner: kubernetes.io/gce-pd parameters: type: pd-ssd ``` You may also want to set additional parameters as documented in the list of Kubernetes [Kubernetes documentation](https://kubernetes.io/docs/concepts/storage/storage-classes/), such as configuring the `iopsPerGB` if you're creating a `StorageClass` for AWS's `io1` Provisioned IOPS volume type. You can configure this new disk type to only be used by CockroachDB nodes or as the default for all volumes in your cluster: #### Configure the disk type used by CockroachDB To use a new `StorageClass` without making it the default in your cluster, modify your application's YAML file to ask for it. In the CockroachDB configuration, that means adding `storageClassName` to `cockroachdb.crdbCluster.dataStore.volumeClaimTemplates`: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: dataStore: volumeClaimTemplate: storageClassName: ``` When running `kubectl create -f` on your modified YAML file, Kubernetes should create volumes using the specified `storageClassName`. #### Change the default disk type To make a new `StorageClass` the default for all volumes in your cluster, run the following `kubectl` commands. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get storageclasses ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAME PROVISIONER ssd kubernetes.io/gce-pd standard (default) kubernetes.io/gce-pd ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl patch storageclass standard -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} storageclass "standard" patched ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl patch storageclass ssd -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} storageclass "ssd" patched ``` ### Disk size On some cloud providers, including all GCP disks and the AWS `io1` disk type, the number of IOPS available to a disk is directly correlated to the size of the disk. In such cases, increasing the size of your disks can significantly improve CockroachDB performance, and decrease the risk of filling them up. Before you create your CockroachDB cluster, modify the `cockroachdb.crdbCluster.dataStore.volumeClaimTemplate` in the CockroachDB YAML file to ask for more space. The following example sets this value to 1TB: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: dataStore: volumeClaimTemplate: spec: resources: requests: storage: 1024Gi ``` Since [GCE disk IOPS scale linearly with disk size](https://cloud.google.com/compute/docs/disks/performance#type_comparison), a 1TiB disk gives 1024 times as many IOPS as a 1GiB disk, which can make a very large difference for write-heavy workloads. ### Local disks The examples thus far assume the use of auto-provisioned, remotely attached disks. However, local disks typically provide better performance than remotely attached disks. For example, SSD Instance Store Volumes outperform EBS Volumes on AWS, and Local SSDs outperform Persistent Disks on GCE. As of v1.14, Kubernetes supports [local volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local). When using local disks, consider using [replication controls](/docs/v26.4/configure-replication-zones) to increase the replication factor of your data from 3 (default) to 5. This is because local disks have a greater chance of experiencing a disk failure than a cloud provider's network-attached disks, which are often replicated underneath the covers. ### Resource requests and limits When you ask Kubernetes to run a pod, you can tell it to reserve certain amounts of CPU or memory for each container in the pod, or to limit the CPU or memory of each container. Setting resource [requests](#resource-requests) or [limits](#resource-limits) can have different implications, depending on your Kubernetes cluster's resource utilization. For the authoritative information on this topic, refer to the [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/). #### Resource requests Resource requests reserve a certain amount of CPU or memory for your container. If you add resource requests to your CockroachDB YAML file, Kubernetes will schedule each CockroachDB pod onto a node with sufficient unreserved resources and ensure the pods are guaranteed the reserved resources using the applicable Linux container primitives. If you are running other workloads in your Kubernetes cluster, setting resource requests is strongly recommended to ensure good performance. If you do not set resource requests, CockroachDB could be starved of CPU cycles or [OOM-stopped](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash) before less important processes. To determine how many resources are usable on your Kubernetes nodes, you can run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl describe nodes ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Name: gke-perf-default-pool-aafee20c-k4t8 [...] Capacity: cpu: 4 memory: 15393536Ki pods: 110 Allocatable: cpu: 3920m memory: 12694272Ki pods: 110 [...] Non-terminated Pods: (2 in total) Namespace Name CPU Requests CPU Limits Memory Requests Memory Limits --------- ---- ------------ ---------- --------------- ------------- kube-system kube-dns-778977457c-kqtlr 260m (6%) 0 (0%) 110Mi (0%) 170Mi (1%) kube-system kube-proxy-gke-perf-default-pool-aafee20c-k4t8 100m (2%) 0 (0%) 0 (0%) 0 (0%) Allocated resources: (Total limits may be over 100 percent, i.e., overcommitted.) CPU Requests CPU Limits Memory Requests Memory Limits ------------ ---------- --------------- ------------- 360m (9%) 0 (0%) 110Mi (0%) 170Mi (1%) ``` In the output, the `Allocatable` field shows the `cpu` and `memory` resources Kubernetes will provide to pods running on the machine. The difference between the machine's `Capacity` and its `Allocatable` resources is taken up by the operating system and Kubernetes' management processes. In the preceding output, `3920m` stands for 3920 "milli-CPUs", or "thousandths of a CPU". Kubernetes runs additional pods in the `kube-system` namespace that are part of the cluster infrastructure. If you want to run CockroachDB on every node in your cluster, you must leave room for these processes, which are essential for the Kubernetes cluster's health. If you are only running CockroachDB on a subset of the Kubernetes machines, you can take up all the `Allocatable` space other than what is used by the `kube-system` pods that are on all the Kubernetes machines, such as `kube-proxy` or the `fluentd` logging agent. On Kubernetes v1.10 or earlier, it is difficult to truly use all of the allocatable space, because you'd have to manually preempt the `kube-system` pods on each machine (by deleting them). When the Kubernetes [Pod Priority](https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/) feature is promoted from alpha to beta and becomes more widely available, you could set the CockroachDB pods to a higher priority, causing the Kubernetes scheduler to preempt and reschedule the `kube-system` pods onto other machines. Once you've picked out an amount of CPU and memory to reserve for Cockroach, configure the resource requests in your CockroachDB YAML file. They should go underneath the `containers` heading. For example, to use most of the available resources on the machines described above, you'd configure the following lines of your values file: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: podTemplate: spec: resources: requests: cpu: 3500m memory: 12300Mi ``` When you initialize the cluster, check that all the CockroachDB pods are scheduled successfully. If you see any get stuck in the pending state, run `kubectl describe pod {podname}` and check the `Events` for information about why they're still pending. You may need to manually preempt pods on one or more nodes by running `kubectl delete pod` on them to make room for the CockroachDB pods. As long as the pods you delete were created by a higher-level Kubernetes object such as a `Deployment`, they'll be safely recreated on another node. #### Resource limits Resource limits cap the resources used by a pod to no more than the provided limit. This makes for more predictable performance because your pods will not be allowed to use any excess capacity on their machines. Pods will not have more resources available to them at some times (e.g., lulls in traffic) than others (e.g., busy periods where the other pods on a machine are also fully utilizing their reserved resources). Resource limits also increase the ["Quality of Service" guaranteed by the Kubernetes runtime](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/resource-qos.md) on Kubernetes v1.8 and earlier, making the pods less likely to be preempted when a machine is oversubscribed. Finally, memory limits in particular define the amount of memory the container perceives as available, which is useful when specifying percentage-based values for the CockroachDB `--cache` and `--max-sql-memory` flags, as in our default configuration file. To set resource limits, in addition to the [resource requests](#resource-requests) described in the preceding section, change the configuration as follows: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: podTemplate: spec: resources: requests: cpu: 3500m memory: 12300Mi limits: memory: 12300Mi ``` Pods will be limited to their reserved resources and are unlikely to be preempted, except in rare cases. This will not improve performance on an underutilized Kubernetes cluster, but provides more predictable performance as other workloads run. > [!CAUTION] > > While setting memory limits is strongly recommended, [setting CPU limits can hurt tail latencies as currently implemented by Kubernetes](https://github.com/kubernetes/kubernetes/issues/51135). Cockroach Labs recommends not setting CPU limits at all, unless you have explicitly enabled the non-default [Static CPU Management Policy](https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/#static-policy) when setting up your Kubernetes cluster. In this case, set CPU limits as integers and match memory limits exactly to their corresponding requests. #### Default resource requests and limits Even if you do not manually set resource requests, they are likely being applied. In many installations of Kubernetes, a [LimitRange](https://kubernetes.io/docs/tasks/administer-cluster/cpu-default-namespace/) is preconfigured for the `default` namespace that applies a default CPU request of `100m`, or one-tenth of a CPU. You can see this configuration by running the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl describe limitranges ``` Experimentally, this does not appear to have a noticeable effect on CockroachDB's performance when a Kubernetes cluster isn't heavily utilized, but do not be surprised if you see CPU requests on your pods that you didn't set. ### Other pods on the same machines as CockroachDB As described in [Resource requests and limits](#resource-requests-and-limits), your Kubernetes cluster will always run pods other than CockroachDB. You can see them by running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get pods --all-namespaces ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAMESPACE NAME READY STATUS RESTARTS AGE kube-system event-exporter-v0.1.7-5c4d9556cf-6v7lf 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-6rvmk 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-m2xgp 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-sfgps 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-szwwn 2/2 Running 0 2m kube-system heapster-v1.4.3-968544ffd-5tsb8 3/3 Running 0 1m kube-system kube-dns-778977457c-4s7vv 3/3 Running 0 1m kube-system kube-dns-778977457c-ls6fq 3/3 Running 0 2m kube-system kube-dns-autoscaler-7db47cb9b7-x2cc4 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-dbn0 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-nr06 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-rc4m 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-trd1 1/1 Running 0 2m kube-system kubernetes-dashboard-768854d6dc-v7ng8 1/1 Running 0 2m kube-system l7-default-backend-6497bcdb4d-2kbh4 1/1 Running 0 2m ``` These ["cluster add-ons"](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons) provide a variety of basic services like managing DNS entries for services within the cluster, powering the Kubernetes dashboard UI, or collecting logs or metrics from all the pods running in the cluster. If you do not like having them take up space in your cluster, you can prevent some of them from running by configuring your Kubernetes cluster appropriately. For example, on GKE, you can create a cluster with the minimal set of add-ons by running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud container clusters create --no-enable-cloud-logging --no-enable-cloud-monitoring --addons="" ``` However, some pods like `kube-proxy` and `kube-dns` are required for compliant Kubernetes clusters. Since there will always be pods other than CockroachDB running in your cluster, it's important to understand and account for the effects of having CockroachDB share a machine with other processes. The more processes there are on the same machine as a CockroachDB pod, the slower and less predictable its performance will likely be. To protect against this, it's strongly recommended to specify [resource requests](#resource-requests) on your CockroachDB pods to provide some level of CPU and memory isolation. Even with resource requests, there can still be contention for shared resources like network I/O or, in [exceptional](https://sysdig.com/blog/container-isolation-gone-wrong/) cases, internal kernel data structures. For these reasons and because of the Kubernetes infrastructure processes running on each machine, CockroachDB running on Kubernetes cannot match the performance of running CockroachDB directly on dedicated machines, although it can get quite close with careful configuration. If setting appropriate resource requests still isn't getting you the performance you expect, consider using [dedicated nodes](#dedicated-nodes). #### Client applications on the same machines as CockroachDB Client applications such as benchmarking applications running on the same machines as CockroachDB are likely to compete for resources. As application load increases, so does the load on CockroachDB processes. The best way to avoid this is to [set resource requests and limits](#resource-requests-and-limits). Alternatively, you can also set [anti-affinity scheduling policies](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity) on your client applications: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: podTemplate: spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - loadgen topologyKey: kubernetes.io/hostname - weight: 99 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - cockroachdb topologyKey: kubernetes.io/hostname ``` The preceding configuration will first prefer to put the `loadgen` pods on different nodes from each other, which is important for the fault tolerance of the `loadgen` pods themselves. As a secondary priority, it will attempt to put the pods on nodes that do not already have a running `CockroachDB` pod. This will ensure the best possible balance of fault tolerance and performance for the load generator and CockroachDB cluster. ### Networking [Kubernetes places significant demands on the underlying network](https://kubernetes.io/docs/concepts/cluster-administration/networking/) in order to provide each pod a routable IP address and isolated Linux network namespace, among other requirements. While the impact is heavily dependent on your Kubernetes cluster's network setup, Docker and Kubernetes' networking abstractions often introduce a performance penalty for high-throughput distributed applications such as CockroachDB. Experimenting with networking can be a way to eke more performance out of your cluster. You can either replace your cluster's networking solution with a more performant one, or bypass most of the networking overhead by using the host machines' networks directly. #### Networking solutions If you aren't using a hosted Kubernetes service, you'll need to choose a [networking solution](https://kubernetes.io/docs/concepts/cluster-administration/networking/#how-to-achieve-this) when creating a Kubernetes cluster. While Cockroach Labs does not endorse any specific networking solutions, note that your choice can meaningfully impact CockroachDB's performance compared to running it outside of Kubernetes. ### Dedicated nodes If your Kubernetes cluster uses heterogeneous hardware, you will likely want to ensure that CockroachDB only runs on specific machines. To optimize performance, it can be beneficial to dedicate those machines exclusively to CockroachDB. For more information, refer to [Pod scheduling](/docs/v26.4/schedule-cockroachdb-operator). # Common Issues to Monitor Source: https://docs.cockroachlabs.com/docs/stable/common-issues-to-monitor This page summarizes how to configure and monitor your cluster to prevent issues commonly encountered with: * [CPU](#cpu) * [Memory](#memory) * [Storage and disk I/O](#storage-and-disk-i/o) ## CPU > [!NOTE] > > In our sizing and production guidance, 1 vCPU is considered equivalent to 1 core in the underlying hardware platform. Issues with CPU most commonly arise when there is insufficient CPU to support the scale of the workload. ### CPU planning Provision enough CPU to support your operational and workload concurrency requirements: | Category | Recommendations | | - | - | | CPU |
  • For cluster stability, Cockroach Labs recommends a *minimum* of **8 vCPUs**, and strongly recommends no fewer than **4 vCPUs** per node. In a cluster with too few CPU resources, foreground client workloads will compete with the cluster's background maintenance tasks.
  • Cockroach Labs does not extensively test clusters with more than **64 vCPUs** per node. This is the recommended *maximum* threshold.
  • Use larger VMs to handle temporary workload spikes and processing [hotspots](/docs/v26.4/understand-hotspots).
  • Use connection pooling to manage workload concurrency. The number of **active** connections across all connection pools **should not exceed 4 times the number of vCPUs** in the cluster by a large amount. A connection is "active" when it is actively executing a query. To monitor active connections, use the [**Active SQL Statements** graph and `sql.statements.active` metric](/docs/v26.4/connection-pooling#monitor-active-connections). For more details, refer to [Size connection pools](/docs/v26.4/connection-pooling#size-connection-pools).
  • For additional CPU recommendations, refer to [Recommended Production Settings](/docs/v26.4/recommended-production-settings#sizing).
| ### CPU monitoring Monitor possible signs of CPU starvation: | Parameter | Description | | - | - | | [Service latency](#service-latency) | The time between when the cluster receives a query and finishes executing the query. | | [CPU usage](#cpu-usage) | The CPU consumption by the CockroachDB node process. | | [Workload concurrency](#workload-concurrency) | The number of SQL statements being executed on the cluster at the same time. | | [LSM health](#lsm-health) | The health of the persistent stores. | | [Node health](#node-health) | The operational status of the nodes. | #### Service latency Degradation in SQL response time is the most common symptom of CPU starvation. It can also be a symptom of [insufficient disk I/O](#storage-and-disk-i/o). * The [**Service Latency: SQL Statements, 99th percentile**](/docs/v26.4/ui-sql-dashboard#service-latency-sql-99th-percentile) and [**Service Latency: SQL Statements, 90th percentile**](/docs/v26.4/ui-sql-dashboard#service-latency-sql-90th-percentile) graphs on the SQL dashboard show the time in nanoseconds between when the cluster [receives a query and finishes executing the query](/docs/v26.4/architecture/sql-layer). This time does not include returning results to the client. If latencies are consistently high, check for: * High [CPU usage](#cpu-usage). * An [I/O bottleneck](#disk-iops). #### CPU usage [Compaction on the storage layer](/docs/v26.4/architecture/storage-layer#compaction) uses CPU to run concurrent worker threads. * The [**CPU Utilization**](/docs/v26.4/ui-overload-dashboard#cpu-utilization) graph on the Hardware and Overload dashboards shows the CPU consumption by the CockroachDB process, and excludes other processes on the node. **Expected values for a healthy cluster**: CPU utilized by CockroachDB should not persistently exceed 80%. Because this metric does not reflect system CPU usage, values above 80% suggest that actual CPU utilization is nearing 100%. If CPU usage is high, check whether [workload concurrency](#workload-concurrency) is exceeding CPU resources. By default, the [storage engine](/docs/v26.4/architecture/storage-layer) uses a compaction concurrency of 3. If you have sufficient IOPS and CPU headroom, you can consider increasing this setting via the `COCKROACH_COMPACTION_CONCURRENCY` environment variable. This may help to reshape the LSM more quickly in [inverted LSM](/docs/v26.4/architecture/storage-layer#inverted-lsms) scenarios; and it can lead to increased overall performance for some workloads. Cockroach Labs **strongly recommends** testing your workload against non-default values of this setting. #### Workload concurrency The number of concurrent active SQL statements should be proportionate to your provisioned CPU. * The [**SQL Queries Per Second**](/docs/v26.4/ui-sql-dashboard#sql-queries-per-second) graph on the Overview and SQL dashboards shows the 10-second moving average of `SELECT`, `UPDATE`, `INSERT`, and `DELETE` statements being executed per second on the cluster or node, as well as `Total queries`. The latest QPS value for the cluster is also displayed with the **Queries per second** counter on the Metrics page. **Expected values for a healthy cluster**: At any time, the total number of connections actively executing SQL statements should not exceed 4 times the number of vCPUs in the cluster. You can find them in the Active Executions view in the [DB Console](/docs/v26.4/ui-statements-page) or [Cloud Console](/docs/cockroachcloud/statements-page). You can find the number of open connections in the [DB Console](/docs/v26.4/ui-sql-dashboard#open-sql-sessions) or [Cloud Console](/docs/cockroachcloud/metrics-sql#open-sql-sessions). For more details on configuring connection pools, see [Size connection pools](/docs/v26.4/connection-pooling#size-connection-pools). If workload concurrency exceeds CPU resources, you will observe: * High [CPU usage](#cpu-usage). * Degradation in [SQL response time](#service-latency). * Over time, an [unhealthy LSM](#lsm-health) and [cluster instability](#node-health). To prevent issues with workload concurrency, [provision sufficient CPU](/docs/v26.4/recommended-production-settings#sizing) and use [connection pooling](/docs/v26.4/recommended-production-settings#connection-pooling) for the workload. #### LSM health Issues at the storage layer, including an [inverted LSM](/docs/v26.4/architecture/storage-layer#inverted-lsms) and high [read amplification](/docs/v26.4/architecture/storage-layer#read-amplification), can be observed when [compaction](/docs/v26.4/architecture/storage-layer#compaction) falls behind due to insufficient CPU or excessively high [recovery and rebalance rates](/docs/v26.4/cluster-setup-troubleshooting#excessive-snapshot-rebalance-and-recovery-rates). * The [**IO Overload**](/docs/v26.4/ui-overload-dashboard#io-overload) graph on the Overload dashboard shows the health of the [persistent stores](/docs/v26.4/architecture/storage-layer), which are implemented as log-structured merge (LSM) trees. Level 0 is the highest level of the LSM tree and consists of files containing the latest data written to the [Pebble storage engine](/docs/v26.4/cockroach-start#storage-engine). For more information about LSM levels and how LSMs work, see [Log-structured Merge-trees](/docs/v26.4/architecture/storage-layer#log-structured-merge-trees). **Expected values for a healthy cluster**: An IO Overload value greater than 1.0 generally indicates an overload in the Pebble LSM tree. High values indicate heavy write load that is causing accumulation of files in level 0. These files are not being compacted quickly enough to lower levels, resulting in a [misshapen LSM](/docs/v26.4/architecture/storage-layer#inverted-lsms). > [!NOTE] > > An unhealthy LSM can be caused by other factors, including [under-provisioned storage](#storage-and-disk-i/o). To correlate this symptom with CPU starvation, check for high [CPU usage](#cpu-usage) and excessive [workload concurrency](#workload-concurrency). * The **Read Amplification** graph on the [Storage Dashboard](/docs/v26.4/ui-storage-dashboard) shows the average number of disk reads per logical SQL statement, also known as the [read amplification](/docs/v26.4/architecture/storage-layer#read-amplification) factor. **Expected values for a healthy cluster**: Read amplification factor should be in the single digits. A value exceeding 50 for 1 hour strongly suggests that the LSM tree has an unhealthy shape. * The `STORAGE` [logging channel](/docs/v26.4/logging-overview#logging-channels) indicates an unhealthy LSM with the following: * Frequent `compaction` status messages. * High-read-amplification warnings, e.g., `sstables (read amplification = 54)`. If compaction has fallen behind and caused an [inverted LSM](/docs/v26.4/architecture/storage-layer#inverted-lsms), throttle your workload concurrency to allow [compaction](/docs/v26.4/architecture/storage-layer#compaction) to catch up and restore a healthy LSM shape. The number of **active** connections across all connection pools **should not exceed 4 times the number of vCPUs** in the cluster by a large amount. A connection is "active" when it is actively executing a query. To monitor active connections, use the [**Active SQL Statements** graph and `sql.statements.active` metric](/docs/v26.4/connection-pooling#monitor-active-connections). If a node is severely impacted, you can [start a new node](/docs/v26.4/cockroach-start) and then [decommission the problematic node](/docs/v26.4/node-shutdown?filters=decommission#remove-nodes). By default, the [storage engine](/docs/v26.4/architecture/storage-layer) uses a compaction concurrency of 3. If you have sufficient IOPS and CPU headroom, you can consider increasing this setting via the `COCKROACH_COMPACTION_CONCURRENCY` environment variable. This may help to reshape the LSM more quickly in [inverted LSM](/docs/v26.4/architecture/storage-layer#inverted-lsms) scenarios; and it can lead to increased overall performance for some workloads. Cockroach Labs **strongly recommends** testing your workload against non-default values of this setting. #### Node health If [issues at the storage layer](#lsm-health) remain unresolved, affected nodes will eventually become unresponsive. * The [**Node status**](/docs/v26.4/ui-cluster-overview-page#node-status) on the Cluster Overview page indicates whether nodes are online (`LIVE`) or have crashed (`SUSPECT` or `DEAD`). * The `/health` endpoint of the [Cluster API](/docs/v26.4/cluster-api) returns a `500` error when a node is unhealthy. * A [Prometheus alert](/docs/v26.4/monitoring-and-alerting#node-is-down) can notify when a node has been down for 15 minutes or more. If nodes have shut down, this can also be caused by [insufficient storage capacity](#storage-capacity). > [!NOTE] > > If the cluster becomes unavailable, the DB Console and Cluster API will also become unavailable. You can continue to monitor the cluster via the [Prometheus endpoint](/docs/v26.4/prometheus-endpoint) and [logs](/docs/v26.4/logging-overview). ## Memory CockroachDB is [resilient](/docs/v26.4/demo-cockroachdb-resilience) to node crashes. However, frequent node restarts caused by [out-of-memory (OOM) crashes](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash) can impact cluster stability and performance. ### Memory planning Provision enough memory and allocate an appropriate portion for data caching: * Provision at least **4 GiB of RAM per vCPU**. * Disable Linux memory swapping. Over-allocating memory on production machines can lead to unexpected performance issues when pages have to be read back into memory. * The default value for `--cache` is 128 MiB. For production deployments, set `--cache` to `25%` or higher. To determine appropriate settings for `--cache` and `--max-sql-memory`, use the following formula:
`(2 * --max-sql-memory) + --cache <= 80% of system RAM
  `
To help guard against [OOM events](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash), CockroachDB sets a soft memory limit using mechanisms in Go. Depending on your hardware and workload, you may not need to manually tune `--max-sql-memory`. Test the configuration with a reasonable workload before deploying it to production. > [!NOTE] > > On startup, if CockroachDB detects that `--max-sql-memory` or `--cache` are set too aggressively, a warning is logged. For additional memory recommendations, refer to [Recommended Production Settings: Memory](/docs/v26.4/recommended-production-settings#memory) and [Recommended Production Setting: Cache and SQL memory size](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). ### Memory monitoring Monitor memory usage and node behavior for [OOM errors](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash): | Metric or event | Description | | - | - | | [Node process restarts](#node-process-restarts) | Nodes restarting after crashes | | [SQL memory usage](#sql-memory-usage) | The memory allocated to the SQL layer | | [Database memory usage](#database-memory-usage) | The memory in use by CockroachDB processes | #### Node process restarts CockroachDB attempts to restart nodes after they crash. Nodes that frequently restart following an abrupt process exit may point to an underlying memory issue. * The [**Node status**](/docs/v26.4/ui-cluster-overview-page#node-status) on the Cluster Overview page indicates whether nodes are online (`LIVE`) or have crashed (`SUSPECT` or `DEAD`). * When deploying on [Kubernetes](/docs/v26.4/kubernetes-overview), the `kubectl get pods` output contains a `RESTARTS` column that tracks the number of restarts for each CockroachDB pod. * The `OPS` [logging channel](/docs/v26.4/logging-overview#logging-channels) will record a [`node_restart` event](/docs/v26.4/eventlog#node_restart) whenever a node rejoins the cluster after being offline. * A [Prometheus alert](/docs/v26.4/monitoring-and-alerting#node-is-restarting-too-frequently) can notify when a node has restarted more than once in the last 10 minutes. ##### Verify OOM errors If you observe nodes frequently restarting, confirm that the crashes are caused by [OOM errors](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash): * Monitor `dmesg` to determine if a node crashed because it ran out of memory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo dmesg | grep -iC 3 "cockroach" ``` The following output indicates the node crashed due to insufficient memory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ host kernel: Out of Memory: Killed process (cockroach). ``` * When deploying on [Kubernetes](/docs/v26.4/kubernetes-overview), run `kubectl logs {pod-name}` and look for OOM errors in the log messages. To prevent OOM crashes, [provision sufficient memory](/docs/v26.4/recommended-production-settings#memory). If all CockroachDB machines are provisioned and configured correctly, either run the CockroachDB process on another node with sufficient memory, or [reduce the memory allocated to CockroachDB](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). If you confirm that nodes are crashing due to OOM errors, also check whether [SQL queries](#sql-memory-usage) may be responsible. #### SQL memory usage An untuned SQL query can consume significant resources and impact the performance of other workloads. * The [**SQL Memory**](/docs/v26.4/ui-sql-dashboard#sql-memory) graph on the SQL dashboard shows the current amount of memory in KiB allocated to the SQL layer. **Expected values for a healthy cluster**: This value should not exceed the [`--max-sql-memory`](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size) size. A healthy threshold is 75% of allocated `--max-sql-memory`. * The "active query dump", enabled by default with the `diagnostics.active_query_dumps.enabled` [cluster setting](/docs/v26.4/cluster-settings), is a record of anonymized active queries that is written to disk when a node is detected to be under memory pressure. You can use the active query dump to correlate specific queries to OOM crashes. Active query dumps have the filename `activequeryprof.{date-and-time}.csv` and are found in the `heap_profiler` directory in the configured [logging directory](/docs/v26.4/configure-logs#logging-directory). They are also included when running [`cockroach debug zip`](/docs/v26.4/cockroach-debug-zip). * A `SHOW STATEMENTS` statement can [identify long-running queries](/docs/v26.4/manage-long-running-queries#identify-long-running-queries) on the cluster that may be consuming excessive memory. * A [`memory budget exceeded`](/docs/v26.4/common-errors#memory-budget-exceeded) error in the logs indicates that `--max-sql-memory`, the memory allocated to the SQL layer, was exceeded by the operation referenced in the error. For guidance on resolving this issue, see [Common Errors](/docs/v26.4/common-errors#memory-budget-exceeded). If you find queries that are consuming too much memory, [cancel the queries](/docs/v26.4/manage-long-running-queries#cancel-long-running-queries) to free up memory usage. For information on optimizing query performance, see [SQL Performance Best Practices](/docs/v26.4/performance-best-practices-overview). We **strongly recommend** adding size limits to all [indexed columns](/docs/v26.4/indexes), which includes columns in [primary keys](/docs/v26.4/primary-key). Values exceeding 1 MiB can lead to [storage layer write amplification](/docs/v26.4/architecture/storage-layer#write-amplification) and cause significant performance degradation or even [crashes due to OOMs (out of memory errors)](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash). To add a size limit using [`CREATE TABLE`](/docs/v26.4/create-table): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE TABLE name (first STRING(100), last STRING(100)); ``` To add a size limit using [`ALTER TABLE ... ALTER COLUMN`](/docs/v26.4/alter-table#alter-column): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER TABLE name ALTER first TYPE STRING(99); ``` #### Database memory usage CockroachDB memory usage includes both accounted memory, such as the amount allocated to `--cache` and `--max-sql-memory`; and unaccounted memory, such as uncollected Go garbage and process overhead. * The [**Memory Usage**](/docs/v26.4/ui-runtime-dashboard#memory-usage) graph on the Runtime dashboard shows the total memory in use by CockroachDB processes. The RSS (resident set size) metric represents actual CockroachDB memory usage from the OS/Linux/pod point of view. The Go and CGo metrics represent memory allocation and total usage from a CockroachDB point of view. **Expected values for a healthy cluster**: Go Allocated will depend on workload but should not exceed [`--max-sql-memory`](/docs/v26.4/cockroach-start#flags) by more than 100%. CGo Allocated should not exceed the [`--cache`](/docs/v26.4/cockroach-start#flags) size and CGo Total should not exceed the [`--cache`](/docs/v26.4/cockroach-start#flags) size by more than 15%. For more context on acceptable memory usage, see [Suspected memory leak](/docs/v26.4/cluster-setup-troubleshooting#suspected-memory-leak). ## Storage and disk I/O The cluster will underperform if storage is not provisioned or configured correctly. This can lead to further issues such as [disk stalls](/docs/v26.4/cluster-setup-troubleshooting#disk-stalls) and node shutdown. ### Storage and disk planning Provision enough storage capacity for CockroachDB data, and configure your volumes to maximize disk I/O: | Category | Recommendations | | - | - | | Storage | - Provision volumes with **320 GiB per vCPU**. - Use dedicated volumes for the CockroachDB [store](/docs/v26.4/cockroach-start#store). Do not share the store volume with any other I/O activity. - Determine where CockroachDB [log files](/docs/v26.4/configure-logs#logging-directory) will be stored: either on the same volume as the main data store or on a separate volume from the main data store. Refer to [Storage considerations for file sinks](/docs/v26.4/logging-best-practices#storage-considerations-for-file-sinks) in Logging Best Practices. - See additional storage recommendations in the [Recommended Production Settings](/docs/v26.4/recommended-production-settings#storage). | | Disk I/O | - Disks must be able to achieve **500 IOPS and 30 MB/s per vCPU**. - Do not use LVM in the I/O path. Dynamically resizing CockroachDB store volumes can result in significant performance degradation. Using LVM snapshots in lieu of CockroachDB [backup and restore](/docs/v26.4/take-full-and-incremental-backups) is also not supported. Use [multiple stores per node](/docs/v26.4/cockroach-start#store) instead. - See additional disk I/O recommendations in the [Recommended Production Settings](/docs/v26.4/recommended-production-settings). | ### Storage and disk monitoring Monitor storage capacity and disk performance: | Metric or event | Description | | - | - | | [Storage capacity](#storage-capacity) | The available and used disk capacity in the CockroachDB [store](/docs/v26.4/cockroach-start#store). | | [Disk IOPS](#disk-iops) | The I/O requests per second. | | [Node heartbeat latency](#node-heartbeat-latency) | The time between [node liveness](/docs/v26.4/cluster-setup-troubleshooting#node-liveness-issues) heartbeats. | | [Command commit latency](#command-commit-latency) | The speed at which [Raft commands](/docs/v26.4/architecture/replication-layer) are being committed by nodes in the cluster. | #### Storage capacity CockroachDB requires disk space in order to accept writes. When a node runs out of disk space, it [shuts down](#node-health) and cannot be restarted until space is freed up. * The [**Capacity**](/docs/v26.4/ui-storage-dashboard#capacity) graph on the Overview and Storage dashboards shows the available and used disk capacity in the CockroachDB [store](/docs/v26.4/cockroach-start#store). **Expected values for a healthy cluster**: Used capacity should not persistently exceed 80% of the total capacity. * A [Prometheus alert](/docs/v26.4/monitoring-and-alerting#node-is-running-low-on-disk-space) can notify when a node has less than 15% of free space remaining. > [!TIP] > > Ensure that you [provision sufficient storage](/docs/v26.4/recommended-production-settings#storage). If storage is correctly provisioned and is running low, CockroachDB automatically creates an emergency ballast file that can free up space. For details, see [Disks filling up](/docs/v26.4/cluster-setup-troubleshooting#disks-filling-up). For instructions on how to free up disk space as quickly as possible after dropping a table, see [How can I free up disk space that was used by a dropped table?](/docs/v26.4/operational-faqs#how-can-i-free-up-disk-space-when-dropping-a-table) #### Disk IOPS Insufficient disk I/O can cause [poor SQL performance](#service-latency) and potentially [disk stalls](/docs/v26.4/cluster-setup-troubleshooting#disk-stalls). * The [**Disk Ops In Progress**](/docs/v26.4/ui-hardware-dashboard#disk-ops-in-progress) graph on the Hardware dashboard shows the number of disk reads and writes in queue. **Expected values for a healthy cluster**: This value should be 0 or single-digit values for short periods of time. If the values persist in double digits, you may have an I/O bottleneck. * The Linux tool `iostat` (part of `sysstat`) can be used to monitor IOPS. In the device status output, `avgqu-sz` corresponds to the **Disk Ops In Progress** metric. If service times persist in double digits on any node, this means that your storage device is saturated and is likely under-provisioned or misconfigured. With insufficient disk I/O, you may also see: * Degradation in [SQL response time](#service-latency). * An [unhealthy LSM](#lsm-health). #### Node heartbeat latency * The [**Node Heartbeat Latency: 99th percentile**](/docs/v26.4/ui-distributed-dashboard#node-heartbeat-latency-99th-percentile) and [**Node Heartbeat Latency: 90th percentile**](/docs/v26.4/ui-distributed-dashboard#node-heartbeat-latency-90th-percentile) graphs on the [Distributed Dashboard](/docs/v26.4/ui-distributed-dashboard) show the time elapsed between node heartbeats. **Expected values for a healthy cluster**: Less than 100ms in addition to the [network latency](/docs/v26.4/ui-network-latency-page) between nodes in the cluster. For the purposes of [Raft replication](/docs/v26.4/architecture/replication-layer#raft) and determining the [leaseholder](/docs/v26.4/architecture/overview) of a [range](/docs/v26.4/architecture/overview), node health is no longer determined by heartbeating a single "liveness range"; instead it is determined using [Leader leases](/docs/v26.4/architecture/replication-layer#leader-leases). However, node heartbeats of a single range are still used to determine: * Whether a node is still a member of a cluster (this is used by [`cockroach node decommission`](/docs/v26.4/cockroach-node#node-decommission)). * Whether a node is dead (in which case [its leases will be transferred away](/docs/v26.4/architecture/replication-layer#how-leases-are-transferred-from-a-dead-node)). * How to avoid placing replicas on dead, decommissioning or unhealthy nodes, and to make decisions about lease transfers. #### Command commit latency * The **Command Commit Latency: 50th percentile** and **Command Commit Latency: 99th percentile** graphs on the [Storage dashboard](/docs/v26.4/ui-storage-dashboard) show how quickly [Raft commands](/docs/v26.4/architecture/replication-layer) are being committed by nodes in the cluster. This is a good signal of I/O load. **Expected values for a healthy cluster**: On SSDs ([strongly recommended](/docs/v26.4/recommended-production-settings#storage)), this should be between 1 and 100 milliseconds. On HDDs, this should be no more than 1 second. ## See also * [Recommended Production Settings](/docs/v26.4/recommended-production-settings) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Common Errors and Solutions](/docs/v26.4/common-errors) * [Operational FAQs](/docs/v26.4/operational-faqs) * [Performance Tuning Recipes](/docs/v26.4/performance-recipes) * [Troubleshoot Cluster Setup](/docs/v26.4/cluster-setup-troubleshooting) * [Troubleshoot SQL Behavior](/docs/v26.4/query-behavior-troubleshooting) * [Admission Control](/docs/v26.4/admission-control) * [Metrics](/docs/v26.4/metrics) * [Alerts Page](/docs/cockroachcloud/alerts-page) (CockroachDB Advanced) # Resource Management Source: https://docs.cockroachlabs.com/docs/stable/configure-cockroachdb-kubernetes This page explains how to configure Kubernetes cluster resources such as memory, CPU, and storage. This page is for Kubernetes deployments that are not using the CockroachDB operator. For guidance specific to the CockroachDB operator, read [Resource management with the CockroachDB operator](/docs/v26.4/configure-cockroachdb-operator). > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). These settings override the defaults used when [deploying CockroachDB on Kubernetes](/docs/v26.4/deploy-cockroachdb-with-kubernetes). > [!NOTE] > > All `kubectl` steps should be performed in the [namespace where you installed the operator](/docs/v26.4/deploy-cockroachdb-with-kubernetes#install-the-operator). By default, this is `cockroach-operator-system`. > [!TIP] > > If you [deployed CockroachDB on Red Hat OpenShift](/docs/v26.4/deploy-cockroachdb-with-kubernetes-openshift), substitute `kubectl` with `oc` in the following commands. On a production cluster, the resources you allocate to CockroachDB should be proportionate to your machine types and workload. We recommend that you determine and set these values before deploying the cluster, but you can also update the values on a running cluster. > [!TIP] > > Run `kubectl describe nodes` to see the available resources on the instances that you have provisioned. ## Memory and CPU You can set the CPU and memory resources allocated to the CockroachDB container on each pod. > [!NOTE] > > 1 CPU in Kubernetes is equivalent to 1 vCPU or 1 hyperthread. For best practices on provisioning CPU and memory for CockroachDB, see the [Production Checklist](/docs/v26.4/recommended-production-settings#hardware). Specify CPU and memory values in `resources.requests` and `resources.limits` in the Public operator's custom resource, which is used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: resources: requests: cpu: "4" memory: "16Gi" limits: cpu: "4" memory: "16Gi" ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f example.yaml ``` Specify CPU and memory values in `resources.requests` and `resources.limits` in the StatefulSet manifest you used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes?filters=manual#configure-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: template: containers: - name: cockroachdb resources: requests: cpu: "4" memory: "16Gi" limits: cpu: "4" memory: "16Gi" ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f {statefulset-manifest}.yaml ``` Specify CPU and memory values in `resources.requests` and `resources.limits` in the custom values file you created when [deploying the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes?filters=helm#step-2-start-cockroachdb): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} statefulset: resources: limits: cpu: "4" memory: "16Gi" requests: cpu: "4" memory: "16Gi" ``` Apply the custom values to override the default Helm chart [values](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm upgrade {release-name} --values {custom-values}.yaml cockroachdb/cockroachdb ``` We recommend using identical values for `resources.requests` and `resources.limits`. When setting the new values, note that not all of a pod's resources will be available to the CockroachDB container. This is because a fraction of the CPU and memory is reserved for Kubernetes. > [!NOTE] > > If no resource limits are specified, the pods will be able to consume the maximum available CPUs and memory. However, to avoid overallocating resources when another memory-intensive workload is on the same instance, always set resource requests and limits explicitly. For more information on how Kubernetes handles resources, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/). ## Cache and SQL memory size Each CockroachDB node reserves a portion of its available memory for its cache and for storing temporary data for SQL queries. For more information on these settings, see the [Production Checklist](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). Our Kubernetes manifests dynamically set cache size and SQL memory size each to 1/4 (the recommended fraction) of the available memory, which depends on the memory request and limit you [specified](#memory-and-cpu) for your configuration. If you want to customize these values, set them explicitly. Specify `cache` and `maxSQLMemory` in the Public operator's custom resource, which is used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: cache: "4Gi" maxSQLMemory: "4Gi" ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f example.yaml ``` > [!NOTE] > > Specifying these values is equivalent to using the `--cache` and `--max-sql-memory` flags with [`cockroach start`](/docs/v26.4/cockroach-start#flags). ## Cache and SQL memory size Each CockroachDB node reserves a portion of its available memory for its cache and for storing temporary data for SQL queries. For more information on these settings, see the [Production Checklist](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). Our Kubernetes manifests dynamically set cache size and SQL memory size each to 1/4 (the recommended fraction) of the available memory, which depends on the memory request and limit you [specified](#memory-and-cpu) for your configuration. If you want to customize these values, set them explicitly. Specify `cache` and `maxSQLMemory` in the custom values file you created when [deploying the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes?filters=helm#step-2-start-cockroachdb): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} conf: cache: "4Gi" max-sql-memory: "4Gi" ``` Apply the custom values to override the default Helm chart [values](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm upgrade {release-name} --values {custom-values}.yaml cockroachdb/cockroachdb ``` ## Persistent storage When you start your cluster, Kubernetes dynamically provisions and mounts a persistent volume into each pod. For more information on persistent volumes, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/storage/persistent-volumes/). The storage capacity of each volume is set in `pvc.spec.resources` in the Public operator's custom resource, which is used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: dataStore: pvc: spec: resources: limits: storage: "60Gi" requests: storage: "60Gi" ``` The storage capacity of each volume is initially set in `volumeClaimTemplates.spec.resources` in the StatefulSet manifest you used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes?filters=manual#configure-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} volumeClaimTemplates: spec: resources: requests: storage: 100Gi ``` The storage capacity of each volume is initially set in the Helm chart's [values file](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} persistentVolume: size: 100Gi ``` You should provision an appropriate amount of disk storage for your workload. For recommendations on this, see the [Production Checklist](/docs/v26.4/recommended-production-settings#storage). ### Expand disk size If you discover that you need more capacity, you can expand the persistent volumes on a running cluster. Increasing disk size is often [beneficial for CockroachDB performance](/docs/v26.4/kubernetes-performance#disk-size). Specify a new volume size in `resources.requests` and `resources.limits` in the Public operator's custom resource, which is used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: dataStore: pvc: spec: resources: limits: storage: "100Gi" requests: storage: "100Gi" ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f example.yaml ``` The Public operator updates the StatefulSet and triggers a rolling restart of the pods with the new storage capacity. To verify that the storage capacity has been updated, run `kubectl get pvc` to view the persistent volume claims (PVCs). It will take a few minutes before the PVCs are completely updated. You can expand certain [types of persistent volumes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#types-of-persistent-volumes) (including GCE Persistent Disk and Amazon Elastic Block Store) by editing their persistent volume claims. > [!NOTE] > > These steps assume you followed the tutorial [Deploy CockroachDB on Kubernetes](/docs/v26.4/deploy-cockroachdb-with-kubernetes?filters=manual). 1. Get the persistent volume claims for the volumes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pvc ``` ``` NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE datadir-cockroachdb-0 Bound pvc-75dadd4c-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 17m datadir-cockroachdb-1 Bound pvc-75e143ca-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 17m datadir-cockroachdb-2 Bound pvc-75ef409a-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 17m ``` 2. In order to expand a persistent volume claim, `AllowVolumeExpansion` in its storage class must be `true`. Examine the storage class: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl describe storageclass standard ``` ``` Name: standard IsDefaultClass: Yes Annotations: storageclass.kubernetes.io/is-default-class=true Provisioner: kubernetes.io/gce-pd Parameters: type=pd-standard AllowVolumeExpansion: False MountOptions: ReclaimPolicy: Delete VolumeBindingMode: Immediate Events: ``` If necessary, edit the storage class: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch storageclass standard -p '{"allowVolumeExpansion": true}' ``` ``` storageclass.storage.k8s.io/standard patched ``` 3. Edit one of the persistent volume claims to request more space: > [!NOTE] > > The requested `storage` value must be larger than the previous value. You cannot use this method to decrease the disk size. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch pvc datadir-cockroachdb-0 -p '{"spec": {"resources": {"requests": {"storage": "200Gi"}}}}' ``` ``` persistentvolumeclaim/datadir-cockroachdb-0 patched ``` 1. Check the capacity of the persistent volume claim: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pvc datadir-cockroachdb-0 ``` ``` NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE datadir-cockroachdb-0 Bound pvc-75dadd4c-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 18m ``` If the PVC capacity has not changed, this may be because `AllowVolumeExpansion` was initially set to `false` or because the [volume has a file system](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#resizing-an-in-use-persistentvolumeclaim) that has to be expanded. You will need to start or restart a pod in order to have it reflect the new capacity. > [!TIP] > > Running `kubectl get pv` will display the persistent volumes with their *requested* capacity and not their actual capacity. This can be misleading, so it's best to use `kubectl get pvc`. 1. Examine the persistent volume claim. If the volume has a file system, you will see a `FileSystemResizePending` condition with an accompanying message: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl describe pvc datadir-cockroachdb-0 ``` ``` Waiting for user to (re-)start a pod to finish file system resize of volume on node. ``` 2. Delete the corresponding pod to restart it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod cockroachdb-0 ``` The `FileSystemResizePending` condition and message will be removed. 3. View the updated persistent volume claim: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pvc datadir-cockroachdb-0 ``` ``` NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE datadir-cockroachdb-0 Bound pvc-75dadd4c-01a1-11ea-b065-42010a8e00cb 200Gi RWO standard 20m ``` 4. The CockroachDB cluster needs to be expanded one node at a time. Repeat steps 3 - 6 to increase the capacities of the remaining volumes by the same amount. You can expand certain [types of persistent volumes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#types-of-persistent-volumes) (including GCE Persistent Disk and Amazon Elastic Block Store) by editing their persistent volume claims. These steps assume you followed the tutorial [Deploy CockroachDB on Kubernetes](/docs/v26.4/deploy-cockroachdb-with-kubernetes?filters=helm). 1. Get the persistent volume claims for the volumes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pvc ``` ``` NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE datadir-my-release-cockroachdb-0 Bound pvc-75dadd4c-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 17m datadir-my-release-cockroachdb-1 Bound pvc-75e143ca-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 17m datadir-my-release-cockroachdb-2 Bound pvc-75ef409a-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 17m ``` 2. In order to expand a persistent volume claim, `AllowVolumeExpansion` in its storage class must be `true`. Examine the storage class: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl describe storageclass standard ``` ``` Name: standard IsDefaultClass: Yes Annotations: storageclass.kubernetes.io/is-default-class=true Provisioner: kubernetes.io/gce-pd Parameters: type=pd-standard AllowVolumeExpansion: False MountOptions: ReclaimPolicy: Delete VolumeBindingMode: Immediate Events: ``` If necessary, edit the storage class: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch storageclass standard -p '{"allowVolumeExpansion": true}' ``` ``` storageclass.storage.k8s.io/standard patched ``` 3. Edit one of the persistent volume claims to request more space: The requested `storage` value must be larger than the previous value. You cannot use this method to decrease the disk size. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch pvc datadir-my-release-cockroachdb-0 -p '{"spec": {"resources": {"requests": {"storage": "200Gi"}}}}' ``` ``` persistentvolumeclaim/datadir-my-release-cockroachdb-0 patched ``` 4. Check the capacity of the persistent volume claim: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pvc datadir-my-release-cockroachdb-0 ``` ``` NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE datadir-my-release-cockroachdb-0 Bound pvc-75dadd4c-01a1-11ea-b065-42010a8e00cb 100Gi RWO standard 18m ``` If the PVC capacity has not changed, this may be because `AllowVolumeExpansion` was initially set to `false` or because the [volume has a file system](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#resizing-an-in-use-persistentvolumeclaim) that has to be expanded. You will need to start or restart a pod in order to have it reflect the new capacity. Running `kubectl get pv` will display the persistent volumes with their *requested* capacity and not their actual capacity. This can be misleading, so it's best to use `kubectl get pvc`. 5. Examine the persistent volume claim. If the volume has a file system, you will see a `FileSystemResizePending` condition with an accompanying message: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl describe pvc datadir-my-release-cockroachdb-0 ``` ``` Waiting for user to (re-)start a pod to finish file system resize of volume on node. ``` 6. Delete the corresponding pod to restart it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod my-release-cockroachdb-0 ``` The `FileSystemResizePending` condition and message will be removed. 7. View the updated persistent volume claim: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pvc datadir-my-release-cockroachdb-0 ``` ``` NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE datadir-my-release-cockroachdb-0 Bound pvc-75dadd4c-01a1-11ea-b065-42010a8e00cb 200Gi RWO standard 20m ``` 8. The CockroachDB cluster needs to be expanded one node at a time. Repeat steps 3 - 6 to increase the capacities of the remaining volumes by the same amount. ## Network ports The Public operator separates network traffic into three ports: | Protocol | Default | Description | Custom Resource Field | | - | - | - | - | | gRPC | 26258 | Used for node connections | `grpcPort` | | HTTP | 8080 | Used to [access the DB Console](/docs/v26.4/ui-overview#db-console-access) | `httpPort` | | SQL | 26257 | Used for SQL shell access | `sqlPort` | Specify alternate port numbers in the Public operator's [custom resource](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster) (for example, to match the default port `5432` on PostgreSQL): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: sqlPort: 5432 ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f example.yaml ``` The Public operator updates the StatefulSet and triggers a rolling restart of the pods with the new port settings. > [!CAUTION] > > Currently, only the pods are updated with new ports. To connect to the cluster, you need to ensure that the `public` service is also updated to use the new port. You can do this by deleting the service with `kubectl delete service {cluster-name}-public`. When service is recreated by the operator, it will use the new port. This is a known limitation. ## Ingress You can configure an [Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/) object to expose an internal HTTP or SQL [`ClusterIP` service](https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types) through a hostname. In order to use the Ingress resource, your cluster must be running an [Ingress controller](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/) for load balancing. This is **not** handled by the Public operator and must be deployed separately. Specify Ingress objects in `ingress.ui` (HTTP) or `ingress.sql` (SQL) in the Public operator's custom resource, which is used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: ingress: ui: ingressClassName: nginx annotations: key: value host: ui.example.com sql: ingressClassName: nginx annotations: key: value host: sql.example.com ``` * `ingressClassName` specifies the [`IngressClass`](https://kubernetes.io/docs/concepts/services-networking/ingress/#ingress-class) of the Ingress controller. This example uses the [nginx](https://kubernetes.github.io/ingress-nginx/) controller. * The `host` must be made publicly accessible. For example, create a route in [Amazon Route 53](https://aws.amazon.com/route53/), or add an entry to `/etc/hosts` that maps the IP address of the Ingress controller to the hostname. > [!NOTE] > > Multiple hosts can be mapped to the same Ingress controller IP. * TCP connections for SQL clients must be enabled for the Ingress controller. For an example, see the [nginx documentation](https://kubernetes.github.io/ingress-nginx/user-guide/exposing-tcp-udp-services/). > [!NOTE] > > Changing the SQL Ingress `host` on a running deployment will cause a rolling restart of the cluster, due to new node certificates being generated for the SQL host. The [custom resource definition](https://github.com/cockroachdb/cockroach-operator/blob/v2.18.3/config/crd/bases/crdb.cockroachlabs.com_crdbclusters.yaml) details the fields supported by the operator. # Resource Management with the CockroachDB Operator Source: https://docs.cockroachlabs.com/docs/stable/configure-cockroachdb-operator This page explains how to configure Kubernetes cluster resources such as memory, CPU, and storage. On a production cluster, the resources you allocate to CockroachDB should be proportionate to your machine types and workload. Cockroach Labs recommends that you determine and set these values before deploying the cluster, but you can also update the values on a running cluster. > [!NOTE] > > Run `kubectl describe nodes` to see the available resources on the instances that you have provisioned. ## Memory and CPU You can set the CPU and memory resources allocated to the CockroachDB container on each pod. > [!NOTE] > > 1 CPU in Kubernetes is equivalent to 1 vCPU or 1 hyperthread. For best practices on provisioning CPU and memory for CockroachDB, refer to the [Production Checklist](/docs/v26.4/recommended-production-settings#hardware). Specify CPU and memory values in `cockroachdb.crdbCluster.podTemplate.spec.resources.limits` and `cockroachdb.crdbCluster.podTemplate.spec.resources.requests` in the values file used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: podTemplate: spec: resources: limits: cpu: 4000m memory: 16Gi requests: cpu: 4000m memory: 16gi ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Generate values.yaml only if it does not already exist locally, then edit it before upgrading [ -f values.yaml ] || helm show values cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} > values.yaml # Apply the edited values.yaml helm upgrade $CRDBCLUSTER cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} -f values.yaml -n $NAMESPACE ``` Cockroach Labs recommends using identical values for `resources.requests` and `resources.limits`. When setting the new values, note that not all of a pod's resources will be available to the CockroachDB container. This is because a fraction of the CPU and memory is reserved for Kubernetes. > [!NOTE] > > If no resource limits are specified, the pods will be able to consume the maximum available CPUs and memory. However, to avoid overallocating resources when another memory-intensive workload is on the same instance, always set resource requests and limits explicitly. For more information on how Kubernetes handles resources, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/). ### Cache and SQL memory size Each CockroachDB node reserves a portion of its available memory for its cache and for storing temporary data for SQL queries. For more information on these settings, see the [Production Checklist](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). The CockroachDB operator dynamically sets cache size and SQL memory size each to 25% (the recommended percentage) of the available memory, which depends on the memory request and limit you [specified](#memory-and-cpu) for your configuration. These values can be modified by adding the `cache` or `max-sql-memory` fields to `cockroachdb.crdbCluster.flags`, which is equivalent to appending `--cache` or `--max-sql-memory` as [cockroach start flags](/docs/v26.4/cockroach-start#flags). ## Persistent storage When you start your cluster, Kubernetes dynamically provisions and mounts a persistent volume into each pod. For more information on persistent volumes, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/storage/persistent-volumes/). The storage capacity of each volume is set in `cockroachdb.crdbCluster.dataStore.volumeClaimTemplate.spec.resources` in the values file used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: dataStore: volumeClaimTemplate: spec: resources: requests: storage: "10Gi" ``` You should provision an appropriate amount of disk storage for your workload. For recommendations on this, see the [Production Checklist](/docs/v26.4/recommended-production-settings#storage). ### Expand disk size If you discover that you need more capacity, you can expand the persistent volumes on a running cluster. Increasing disk size is often [beneficial for CockroachDB performance](/docs/v26.4/cockroachdb-operator-performance). > [!NOTE] > > The volume size should only adjusted on disk types that can dynamically scale up, such as Amazon EBS volumes. Adjusting the volume size on non-dynamically scaling disks is not recommended, and instead you should horizontally scale the number of disks used. Specify a new volume size in the values file used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: dataStore: volumeClaimTemplate: spec: resources: requests: storage: "100Gi" ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Generate values.yaml only if it does not already exist locally, then edit it before upgrading [ -f values.yaml ] || helm show values cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} > values.yaml # Apply the edited values.yaml helm upgrade $CRDBCLUSTER cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} -f values.yaml -n $NAMESPACE ``` The CockroachDB operator updates all nodes and triggers a rolling restart of the pods with the new storage capacity. To verify that the storage capacity has been updated, run `kubectl get pvc` to view the persistent volume claims (PVCs). It will take a few minutes before the PVCs are completely updated. ## Network ports The CockroachDB operator separates network traffic into three ports: | Protocol | Default Port | Description | Custom Resource Field | | - | - | - | - | | gRPC | 26258 | Used for node connections | service.ports.grpc | | HTTP | 8080 | Used to access the DB Console | service.ports.http | | SQL | 26257 | Used for SQL shell access | service.ports.sql | Specify alternate port numbers in `cockroachdb.crdbCluster.service.ports` of the 's [custom resource](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster) (for example, to match the default port `5432` on PostgreSQL): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: service: ports: sql: 5432 ``` Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Generate values.yaml only if it does not already exist locally, then edit it before upgrading [ -f values.yaml ] || helm show values cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} > values.yaml # Apply the edited values.yaml helm upgrade $CRDBCLUSTER cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} -f values.yaml -n $NAMESPACE ``` The CockroachDB operator updates all nodes and triggers a rolling restart of the pods with the new port settings. ## Ingress You can configure an [Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/) object to expose an internal HTTP or SQL [`ClusterIP` service](https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types) through a hostname. In order to use the Ingress resource, your cluster must be running an [Ingress controller](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/) for load balancing. This is **not** handled by the CockroachDB operator and must be deployed separately. Specify Ingress objects in `cockroachdb.crdbCluster.service.ingress`. Set `ingress.enabled` to `true` and specify `ingress.ui` (HTTP) or `ingress.sql` (SQL) in the values file used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: service: ingress: enabled: true ui: ingressClassName: nginx annotations: key: value host: ui.example.com sql: ingressClassName: nginx annotations: key: value host: sql.example.com ``` * `ingressClassName` specifies the [`IngressClass`](https://kubernetes.io/docs/concepts/services-networking/ingress/#ingress-class) of the Ingress controller. This example uses the [nginx](https://kubernetes.github.io/ingress-nginx/) controller. * The `host` must be made publicly accessible. For example, create a route in [Amazon Route 53](https://aws.amazon.com/route53/), or add an entry to `/etc/hosts` that maps the IP address of the Ingress controller to the hostname. > [!NOTE] > > Multiple hosts can be mapped to the same Ingress controller IP. * TCP connections for SQL clients must be enabled for the Ingress controller. For an example, see the [nginx documentation](https://kubernetes.github.io/ingress-nginx/user-guide/exposing-tcp-udp-services/). > [!NOTE] > > Changing the SQL Ingress `host` on a running deployment will cause a rolling restart of the cluster, due to new node certificates being generated for the SQL host. # Connect to a CockroachDB Cluster Source: https://docs.cockroachlabs.com/docs/stable/connect-to-the-database This page documents the required connection configuration for [fully-supported third-party tools](/docs/v26.4/third-party-database-tools). For a list of all supported cluster connection parameters, see the [`cockroach` Connection Parameters](/docs/v26.4/connection-parameters). For a list of community-supported third-party tools, see [Third-Party Tools Supported by the Community](/docs/v26.4/community-tooling). CockroachDB supports both native drivers and the PostgreSQL wire protocol. Most client drivers and ORM frameworks connect to CockroachDB like they connect to PostgreSQL. ## Step 1. Select your deployment > [tab] CockroachDB Basic/Standard > > To connect to a CockroachDB Cloud cluster, you need a general connection string or connection parameters, which include the username, host, database, and port. To find these, open the **Connect** dialog for your cluster in the [CockroachDB Cloud Console](https://cockroachlabs.cloud) and select either **General connection string** or **Parameters only** as the option. > [tab] CockroachDB Advanced > > To connect to a CockroachDB Cloud cluster, you need a general connection string or connection parameters, which include the username, host, database, and port. To find these, open the **Connect** dialog for your cluster in the [CockroachDB Cloud Console](https://cockroachlabs.cloud) and select either **General connection string** or **Parameters only** as the option. > [tab] CockroachDB self-hosted > > To connect to a CockroachDB self-hosted cluster, you need the [general connection string](/docs/v26.4/connection-parameters#connect-using-a-url) or [connection parameters](/docs/v26.4/connection-parameters#connect-using-discrete-parameters) for your cluster. > > The connection strings and parameters for your cluster are output when you [start the cluster](/docs/v26.4/cockroach-start#standard-output). ## Step 2. Select your language and driver > [tab] JavaScript/TypeScript > > > [tab] node-postgres > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > $env:DATABASE_URL = "{connection string}" > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [node-postgres](https://node-postgres.com), create a new [`Client`](https://node-postgres.com/apis/client) object with a connection string. > > > > For example: > > > > ```js theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > const { Client } = require('pg') > > > > const client = new Client(process.env.DATABASE_URL) > > > > client.connect() > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > For more information about connecting with node-postgres, see the [official node-postgres documentation](https://node-postgres.com/features/connecting). > > > [tab] Sequelize > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > $env:DATABASE_URL = "{connection string}" > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [Sequelize](https://sequelize.org), create a `Sequelize` object with the [CockroachDB Sequelize adapter](https://github.com/cockroachdb/sequelize-cockroachdb). > > > > For example: > > > > ```js theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > const Sequelize = require("sequelize-cockroachdb"); > > > > const connectionString = process.env.DATABASE_URL > > const sequelize = new Sequelize(connectionString) > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > > [!NOTE] > > > > > > To connect to CockroachDB with Sequelize, you must install the [CockroachDB Sequelize adapter](https://github.com/cockroachdb/sequelize-cockroachdb). > > > > > > For more information about connecting with Sequelize, see the [official Sequelize documentation](https://sequelize.org/docs/v6/). > > > [tab] TypeORM > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database} > > > ``` > > > > > > TypeORM configures SSL separately in the DataSource object (`ssl: true`). > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database} > > > ``` > > > > > > TypeORM configures SSL separately in the DataSource object: > > > > > > ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > ssl: { > > > ca: process.env.CA_CERT > > > } > > > ``` > > > > > > Where `CA_CERT` is an environment variable set to the root certificate [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database} > > > ``` > > > > > > TypeORM configures SSL separately in the DataSource object: > > > > > > ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > ssl: { > > > ca: process.env.CA_CERT, > > > key: process.env.CLIENT_KEY, > > > cert: process.env.CLIENT_CERT > > > } > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > $env:DATABASE_URL = "{connection string}" > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [TypeORM](https://typeorm.io), update your project's [`DataSource`](https://typeorm.io/data-source) with the required connection properties. > > > > For example, suppose that you are defining the `DataSource` for your application in a file named `datasource.ts`: > > > > > [tab] CockroachDB Basic/Standard > > > > > > ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > export const AppDataSource = new DataSource({ > > > type: "cockroachdb", > > > url: process.env.DATABASE_URL, > > > ssl: true, > > > ... > > > }); > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > export const AppDataSource = new DataSource({ > > > type: "cockroachdb", > > > url: process.env.DATABASE_URL, > > > ssl: { > > > ca: process.env.CA_CERT > > > }, > > > ... > > > }); > > > ``` > > > > > > Where `CA_CERT` is an environment variable set to the root certificate [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). > > > > > [tab] CockroachDB self-hosted > > > > > > ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > export const AppDataSource = new DataSource({ > > > type: "cockroachdb", > > > url: process.env.DATABASE_URL, > > > ssl: { > > > ca: process.env.CA_CERT, > > > key: process.env.CLIENT_KEY, > > > cert: process.env.CLIENT_CERT > > > }, > > > ... > > > }); > > > ``` > > > > > > Where: > > > > > > * `CA_CERT` is an environment variable set to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/v26.4/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/v26.4/create-security-certificates-custom-ca). > > > * `CLIENT_KEY` is an environment variable set to the [client key](/docs/v26.4/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/v26.4/cockroach-cert#subcommands). > > > * `CLIENT_CERT` is an environment variable set to the [client certificate](/docs/v26.4/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/v26.4/cockroach-cert#subcommands). > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > You can then import the `AppDataSource` into any file in your project and call `AppDataSource.initialize()` to connect to CockroachDB: > > > > ```ts theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > AppDataSource.initialize() > > .then(async () => { > > // Execute operations > > }); > > ``` > > > > For more information about connecting with TypeORM, see the [official TypeORM documentation](https://typeorm.io/#/). > > > [tab] Prisma > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > $env:DATABASE_URL = "{connection string}" > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [Prisma](https://prisma.io/), set the `url` field of the `datasource` block in your Prisma schema to your database connection URL: > > > > ```js theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > generator client { > > provider = "prisma-client-js" > > } > > > > datasource db { > > provider = "cockroachdb" > > url = env("DATABASE_URL") > > } > > > > model Widget { > > id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid > > } > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > For more information about connecting with Prisma, see the [official Prisma documentation](https://www.prisma.io/cockroachdb). > [tab] Python > > > [!NOTE] > > > > To connect to a CockroachDB Basic or Standard cluster from a Python application, you must have a valid CA certificate located at `~/.postgresql/root.crt`. > > > > For instructions on downloading a CA certificate from the CockroachDB Cloud Console, see [Connect to a CockroachDB Basic Cluster](https://www.cockroachlabs.com/docs/cockroachcloud/connect-to-a-basic-cluster) or [Connect to a CockroachDB Standard Cluster](https://www.cockroachlabs.com/docs/cockroachcloud/connect-to-your-cluster). > > > [tab] Psycopg2 > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [Psycopg2](https://www.psycopg.org), pass a connection string to the [`psycopg2.connect` function](https://www.psycopg.org/docs/connection.html). > > > > For example: > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > import psycopg2 > > import os > > > > conn = psycopg2.connect(os.environ['DATABASE_URL']) > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > For more information about connecting with Psycopg, see the [official Psycopg documentation](https://www.psycopg.org/docs). > > > [tab] Psycopg3 > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [Psycopg3](https://www.psycopg.org), pass a connection string to the [`psycopg.connect` function](https://www.psycopg.org/psycopg3/docs/basic/usage.html). > > > > For example: > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > import psycopg > > import os > > > > with psycopg.connect(os.environ['DATABASE_URL']) as conn: > > # application logic here > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > For more information about connecting with Psycopg, see the [official Psycopg documentation](https://www.psycopg.org/psycopg3/docs/basic/index.html). > > > [tab] SQLAlchemy > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > cockroachdb://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > cockroachdb://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > cockroachdb://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [SQLAlchemy](http://docs.sqlalchemy.org/), [create an `Engine` object](https://docs.sqlalchemy.org/core/engines.html) by passing the connection string to the `create_engine` function. > > > > For example: > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > from sqlalchemy import create_engine > > import os > > > > engine = create_engine(os.environ['DATABASE_URL']) > > engine.connect() > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > > [!NOTE] > > > > > > To connect to CockroachDB with SQLAlchemy, you must install the [CockroachDB SQLAlchemy adapter](https://github.com/cockroachdb/sqlalchemy-cockroachdb). > > > > > > For more information about connecting with SQLAlchemy, see the [official SQLAlchemy documentation](https://docs.sqlalchemy.org/core/engines_connections.html). > > > > > > In order for SQLAlchemy to use the CockroachDB adapter, the connection string must begin with `cockroachdb://`. You can use the following code to modify the general connection string, which begins with `postgresql://`, to the format that works with SQLAlchemy and the CockroachDB adapter: > > > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > engine = create_engine(os.environ['DATABASE_URL'].replace("postgresql://", "cockroachdb://")) > > > engine.connect() > > > ``` > > > [tab] Django > > > > ### Connection string format > > > > Django does not use a connection string. Instead, you configure connection parameters in the `DATABASES` property in your project's `settings.py` file. > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Connect to the cluster > > > > To connect to CockroachDB from a [Django](https://www.djangoproject.com) application, update the `DATABASES` property in the project's `settings.py` file. > > > > > [tab] CockroachDB Basic/Standard > > > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > ## settings.py > > > > > > ... > > > > > > DATABASES = { > > > 'default': { > > > 'ENGINE': 'django_cockroachdb', > > > 'NAME': '{database}', > > > 'USER': '{username}', > > > 'PASSWORD': '{password}', > > > 'HOST': '{host}', > > > 'PORT': '{port}', > > > 'OPTIONS': { > > > 'sslmode': 'verify-full' > > > }, > > > }, > > > } > > > > > > ... > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > ## settings.py > > > > > > ... > > > > > > DATABASES = { > > > 'default': { > > > 'ENGINE': 'django_cockroachdb', > > > 'NAME': '{database}', > > > 'USER': '{username}', > > > 'PASSWORD': '{password}', > > > 'HOST': '{host}', > > > 'PORT': '{port}', > > > 'OPTIONS': { > > > 'sslmode': 'verify-full', > > > 'sslrootcert': os.path.expandvars('{root-cert}'), > > > }, > > > }, > > > } > > > > > > ... > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > > ## settings.py > > > > > > ... > > > > > > DATABASES = { > > > 'default': { > > > 'ENGINE': 'django_cockroachdb', > > > 'NAME': '{database}', > > > 'USER': '{username}', > > > 'HOST': '{host}', > > > 'PORT': '{port}', > > > 'OPTIONS': { > > > 'sslmode': 'verify-full', > > > 'sslrootcert': os.path.expandvars('{root-cert}'), > > > 'sslcert': os.path.expandvars('{client-cert}'), > > > 'sslkey': os.path.expandvars('{client-key}'), > > > }, > > > }, > > > } > > > > > > ... > > > ``` > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > > [!NOTE] > > > > > > To connect to CockroachDB with Django, you must install the [CockroachDB Django adapter](https://github.com/cockroachdb/django-cockroachdb). > > > > > > For more information about connecting with Django, see the [official Django documentation](https://docs.djangoproject.com/en/4.0/). > [tab] Go > > > [tab] pgx > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [pgx](https://github.com/jackc/pgx), use the `pgx.Connect` function. > > > > For example: > > > > ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > package main > > > > import ( > > "context" > > "log" > > "os" > > > > "github.com/jackc/pgx/v4" > > ) > > > > func main() { > > conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) > > if err != nil { > > log.Fatal(err) > > } > > defer conn.Close(context.Background()) > > } > > ``` > > > > For more information about connecting with pgx, see the [official pgx documentation](https://pkg.go.dev/github.com/jackc/pgx). > > > [tab] pq > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [pq](https://godoc.org/github.com/lib/pq), use the [`sql.Open` function](https://go.dev/doc/tutorial/database-access). > > > > For example: > > > > ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > package main > > > > import ( > > "database/sql" > > "log" > > "os" > > > > _ "github.com/lib/pq" > > ) > > > > func main() { > > db, err := sql.Open("postgres", os.Getenv("DATABASE_URL")) > > if err != nil { > > log.Fatal(err) > > } > > defer db.Close() > > } > > ``` > > > > For more information about connecting with pq, see the [official pq documentation](https://pkg.go.dev/github.com/lib/pq). > > > [tab] GORM > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [GORM](http://gorm.io), use the `gorm.Open` function, with the GORM `postgres` driver. > > > > For example: > > > > ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > package main > > > > import ( > > "log" > > "os" > > > > "gorm.io/driver/postgres" > > "gorm.io/gorm" > > ) > > > > func main() { > > db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{}) > > if err != nil { > > log.Fatal(err) > > } > > } > > ``` > > > > For more information about connecting with GORM, see the [official GORM documentation](https://gorm.io/docs). > [tab] Java > > > [tab] JDBC > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > jdbc:postgresql://{host}:{port}/{database}?password={password}&sslmode=verify-full&user={username} > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > jdbc:postgresql://{host}:{port}/{database}?user={username}&password={password}&sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > jdbc:postgresql://{host}:{port}/{database}?user={username}&sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the [PKCS#8](https://tools.ietf.org/html/rfc5208)-formatted [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client --also-generate-pkcs8-key`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `JDBC_DATABASE_URL` environment variable to your JDBC connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export JDBC_DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > $env:JDBC_DATABASE_URL = "{connection string}" > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with the [JDBC](https://jdbc.postgresql.org) driver, create a `DataSource` object ([`PGSimpleDataSource` or `PGPoolingDataSource`](https://jdbc.postgresql.org/documentation/datasource/#applications-datasource)), and set the connection string with the `setUrl` class method. > > > > For example: > > > > ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > PGSimpleDataSource ds = new PGSimpleDataSource(); > > ds.setUrl(System.getenv("JDBC_DATABASE_URL")); > > ``` > > > > Where `JDBC_DATABASE_URL` is an environment variable set to a valid JDBC-compatible CockroachDB connection string. > > > > For more information about connecting with JDBC, see the [official JDBC documentation](https://jdbc.postgresql.org/documentation/). > > > [tab] Hibernate > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > jdbc:postgresql://{host}:{port}/{database}?password={password}&sslmode=verify-full&user={username} > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > jdbc:postgresql://{host}:{port}/{database}?user={username}&password={password}&sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > jdbc:postgresql://{host}:{port}/{database}?user={username}&sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The [URL-encoded](https://wikipedia.org/wiki/Percent-encoding) path to the [PKCS#8](https://tools.ietf.org/html/rfc5208)-formatted [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client --also-generate-pkcs8-key`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `JDBC_DATABASE_URL` environment variable to your JDBC connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export JDBC_DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > $env:JDBC_DATABASE_URL = "{connection string}" > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [Hibernate](https://hibernate.org/orm) ORM, set the object's `hibernate.connection.url` property to a valid CockroachDB connection string. > > > > For example, if you are bootstrapping your application with a [`ServiceRegistry`](https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#bootstrap-native-registry) object, first read from the Hibernate configuration file, and then set the `hibernate.connection.url` with the `applySetting` class method: > > > > ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() > > .configure( "hibernate.cfg.xml" ).applySetting("hibernate.connection.url", System.getenv("JDBC_DATABASE_URL")) > > .build(); > > > > Metadata metadata = new MetadataSources( standardRegistry ) > > .getMetadataBuilder() > > .build(); > > > > SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() > > .build(); > > ``` > > > > Where `JDBC_DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > > [!NOTE] > > > > > > To connect to CockroachDB with Hibernate, you must specify the [CockroachDB Hibernate dialect](/docs/v26.4/install-client-drivers?filters=java#hibernate) in your `hibernate.cfg.xml` configuration file. > > > > > > For more information about connecting with Hibernate, see the [official Hibernate documentation](https://hibernate.org/orm/documentation). > [tab] Ruby > > > [!NOTE] > > > > To connect to a CockroachDB Basic or Standard cluster from a Ruby application, you must have a valid CA certificate located at `~/.postgresql/root.crt`. > > > > For instructions on downloading a CA certificate from the CockroachDB Cloud Console, see [Connect to a CockroachDB Basic Cluster](https://www.cockroachlabs.com/docs/cockroachcloud/connect-to-a-basic-cluster) or [Connect to a CockroachDB Standard Cluster](https://www.cockroachlabs.com/docs/cockroachcloud/connect-to-your-cluster). > > > [tab] pg > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > postgresql://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with the [Ruby pg](https://rubygems.org/gems/pg) driver, use the `PG.connect` function. > > > > For example: > > > > ```ruby theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > #!/usr/bin/env ruby > > > > require 'pg' > > > > conn = PG.connect(ENV['DATABASE_URL']) > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > For more information about connecting with pg, see the [official pg documentation](https://www.rubydoc.info/gems/pg). > > > [tab] Active Record > > > > ### Connection string format > > > > > [tab] CockroachDB Basic/Standard > > > > > > ``` > > > cockroachdb://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full > > > ``` > > > > > [tab] CockroachDB Advanced > > > > > > ``` > > > cockroachdb://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert} > > > ``` > > > > > [tab] CockroachDB self-hosted > > > > > > ``` > > > cockroachdb://{username}@{host}:{port}/{database}?sslmode=verify-full&sslrootcert={root-cert}&sslcert={client-cert}&sslkey={client-key} > > > ``` > > > > > > > [!NOTE] > > > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.4/secure-a-cluster). > > > > **Connection parameters** > > > > > [tab] CockroachDB Basic/Standard > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > > > [tab] CockroachDB Advanced > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{password}` | The password for the SQL user connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate that you [downloaded from the CockroachDB Cloud Console](/docs/cockroachcloud/authentication#node-identity-verification). | > > > > > [tab] CockroachDB Core > > > > > > | Parameter | Description | > > > | - | - | > > > | `{username}` | The [SQL user](/docs/stable/security-reference/authorization#sql-users) connecting to the cluster. | > > > | `{host}` | The host on which the CockroachDB node is running. | > > > | `{port}` | The port at which the CockroachDB node is listening. | > > > | `{database}` | The name of the (existing) database. | > > > | `{root-cert}` | The path to the root certificate. You can generate this certificate with [`cockroach cert create-ca`](/docs/stable/cockroach-cert#subcommands), or you can use a [custom CA cert](/docs/stable/create-security-certificates-custom-ca). | > > > | `{client-cert}` | The path to the [client certificate](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this certificate with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > | `{client-key}` | The path to the [client key](/docs/stable/cockroach-cert#client-key-and-certificates) for the user connecting to the cluster. You can generate this key with [`cockroach cert create-client`](/docs/stable/cockroach-cert#subcommands). | > > > > > > The connection information shown on this page uses [client certificate and key authentication](/docs/cockroachcloud/authentication) to connect to a secure, CockroachDB self-hosted cluster. > > > > > > To connect to a CockroachDB self-hosted cluster with client certificate and key authentication, you must first [generate server and client certificates](/docs/cockroachcloud/authentication). > > > > > > For instructions on starting a secure cluster, see [Start a Local Cluster (Secure)](/docs/v26.2/secure-a-cluster). > > > > ### Set environment variable > > > > Set a `DATABASE_URL` environment variable to your connection string: > > > > ```shell Mac or Linux theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > export DATABASE_URL="{connection string}" > > ``` > > > > ```shell Windows theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > set DATABASE_URL={connection string} > > ``` > > > > ### Connect to the cluster > > > > To connect to CockroachDB with [Active Record](https://github.com/rails/rails/tree/main/activerecord) from a Rails app, update the database configuration in `config/database.yml`: > > > > ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > default: &default > > adapter: cockroachdb > > url: <%= ENV['DATABASE_URL'] %> > > > > ... > > ``` > > > > Where `DATABASE_URL` is an environment variable set to a valid CockroachDB connection string. > > > > > [!NOTE] > > > > > > To connect to CockroachDB with Active Record, you must install the [Active Record CockroachDB adapter](https://rubygems.org/gems/activerecord-cockroachdb-adapter). > > > > > > For more information about connecting with Active Record, see the [official Active Record documentation](https://guides.rubyonrails.org/active_record_querying.html). ## See also * [Install a Driver or ORM Framework](/docs/v26.4/install-client-drivers) * [Connection Pooling](/docs/v26.4/connection-pooling) * [`cockroach` Connection Parameters](/docs/v26.4/connection-parameters) # Client Connection Parameters Source: https://docs.cockroachlabs.com/docs/stable/connection-parameters Client applications, including [`cockroach` client commands](/docs/v26.4/cockroach-commands), work by establishing a network connection to a CockroachDB cluster. The client connection parameters determine which CockroachDB cluster they connect to, and how to establish this network connection. ## Supported connection parameters Most client apps, including `cockroach` client commands, determine which CockroachDB server to connect to using a [PostgreSQL connection URL](#connect-using-a-url). When using a URL, a client can also specify additional SQL-level parameters. This mode provides the most configuration flexibility. In addition, all `cockroach` client commands also accept [discrete connection parameters](#connect-using-discrete-parameters) that can specify the connection parameters separately from a URL. ## When to use a URL and when to use discrete parameters Specifying client parameters using a URL may be more convenient during experimentation, as it facilitates copy-pasting the connection parameters (the URL) between different tools: the output of `cockroach start`, other `cockroach` commands, GUI database visualizer, programming tools, etc. Discrete parameters may be more convenient in automation, where the components of the configuration are filled in separately from different variables in a script or a service manager. ## Connect using a URL A connection URL has the following format: ``` postgres:// [!NOTE] > > For `cockroach` commands that accept a URL, you can specify the URL with the command-line flag `--url`. > If `--url` is not specified but > the environment variable `COCKROACH_URL` is defined, the environment > variable is used. Otherwise, the `cockroach` command will use > [discrete connection parameters](#connect-using-discrete-parameters) > as described below. The `= [!NOTE] > > Note that some drivers require certain characters to be properly encoded in URL connection strings. For example, spaces in [a JDBC connection string](https://jdbc.postgresql.org/documentation/use/#connection-parameters) must be specified as `%20`. ### Secure connections with URLs The following values are supported for `sslmode`, although only the first and the last are recommended for use. | Parameter | Description | Recommended for use | | - | - | - | | `sslmode=disable` | Do not use an encrypted, secure connection at all. | Use during development. | | `sslmode=allow` | Enable a secure connection only if the server requires it. **Not supported in all clients.** | | `sslmode=prefer` | Try to establish a secure connection, but accept an insecure connection if the server does not support secure connections. **Not supported in all clients.** | | `sslmode=require` | Force a secure connection. An error occurs if the secure connection cannot be established. | | `sslmode=verify-ca` | Force a secure connection and verify that the server certificate is signed by a known CA. | | `sslmode=verify-full` | Force a secure connection, verify that the server certificate is signed by a known CA, and verify that the server address matches that specified in the certificate. | Use for [secure deployments](/docs/v26.4/secure-a-cluster). | > [!CAUTION] > > Some client drivers and the `cockroach` commands do not support > `sslmode=allow` and `sslmode=prefer`. Check the documentation of your > SQL driver to determine whether these options are supported. ### Convert a URL for different drivers The subcommand `cockroach convert-url` converts a connection URL, such as those printed out by [`cockroach start`](/docs/v26.4/cockroach-start) or included in the online documentation, to the syntax recognized by various [client drivers](/docs/v26.4/third-party-database-tools#drivers). > [!NOTE] > > The `cockroach encode-uri` command has been deprecated and merged into `cockroach convert-url`. Use `cockroach convert-url --format crdb` instead. The `encode-uri` command will be removed in a future release. #### Basic usage By default, `convert-url` outputs the URL in multiple formats: ``` $ ./cockroach convert-url --url "postgres://foo/bar" ``` ``` # Connection URL for libpq (C/C++), psycopg (Python), lib/pq & pgx (Go), node-postgres (JS) and most pq-compatible drivers: postgresql://root@foo:26257/bar # Connection DSN (Data Source Name) for Postgres drivers that accept DSNs - most drivers and also ODBC: database=bar user=root host=foo port=26257 # Connection URL for JDBC (Java and JVM-based languages): jdbc:postgresql://foo:26257/bar?user=root # Direct URL to CockroachDB: postgresql://root@foo:26257/bar ``` #### Specify output format Use the `--format` flag to output a specific format: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach convert-url --url "postgres://foo/bar" --format jdbc ``` ``` jdbc:postgresql://foo:26257/bar?user=root ``` Supported formats: | Format | Description | | - | - | | `pq` | Connection URL for libpq (C/C++), psycopg (Python), lib/pq & pgx (Go), node-postgres (JS), and most pq-compatible drivers | | `dsn` | Data Source Name for Postgres drivers that accept DSNs and ODBC | | `jdbc` | Connection URL for JDBC (Java and JVM-based languages) | | `crdb` | CockroachDB-specific URL format with inlined certificates for [Physical Cluster Replication](/docs/v26.4/physical-cluster-replication-overview) and [Logical Data Replication](/docs/v26.4/logical-data-replication-overview) | #### Generate URLs for replication To generate a connection URL for [Physical Cluster Replication](/docs/v26.4/physical-cluster-replication-overview) or [Logical Data Replication](/docs/v26.4/logical-data-replication-overview), use the `--format crdb` flag with the `--inline` flag to inline certificates directly into the URL: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach convert-url --url "postgresql://{user}:{password}@{node IP}:26257" --format crdb --ca-cert {path to CA certificate} --inline ``` The `--inline` flag automatically sets `--format crdb`, so you can also use: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach convert-url --url "postgresql://{user}:{password}@{node IP}:26257" --ca-cert {path to CA certificate} --inline ``` #### Additional flags | Flag | Description | | - | - | | `--url` | Connection URL to convert (required) | | `--format` | Output format: `pq`, `dsn`, `jdbc`, or `crdb` | | `--inline` | Inline certificates into the URL (automatically sets `--format crdb`) | | `--database` | Database name | | `--user` | Username | | `--password` | Password | | `--cluster` | Cluster name (sets `options=-ccluster= [!NOTE] > > The `options=-c search_path=max_schema` parameter is URL-encoded in the example above. ## Connect using discrete parameters Most [`cockroach` commands](/docs/v26.4/cockroach-commands) accept connection parameters as separate, discrete command-line flags, in addition (or in replacement) to `--url` which [specifies all parameters as a URL](#connect-using-a-url). For each command-line flag that directs a connection parameter, CockroachDB also recognizes an environment variable. The environment variable is used when the command-line flag is not specified. | Flag | Description | | - | - | | `--url` | A [connection URL](/docs/v26.4/connection-parameters#connect-using-a-url) to use instead of the other arguments. To convert a connection URL to the syntax that works with your client driver, run [`cockroach convert-url`](/docs/v26.4/connection-parameters#convert-a-url-for-different-drivers). **Env Variable:** `COCKROACH_URL` **Default:** no URL | | `--host` | The server host and port number to connect to. This can be the address of any node in the cluster. **Env Variable:** `COCKROACH_HOST` **Default:** `localhost:26257` | | `--port` `-p` | The server port to connect to. Note: The port number can also be specified via `--host`. **Env Variable:** `COCKROACH_PORT` **Default:** `26257` | | `--user` `-u` | The [SQL user](/docs/v26.4/create-user) that will own the client session. **Env Variable:** `COCKROACH_USER` **Default:** `root` | | `--insecure` | Use an insecure connection. **Env Variable:** `COCKROACH_INSECURE` **Default:** `false` | | `--cert-principal-map` | A comma-separated list of ` [!NOTE] > > When using discrete connection parameters, the file names of the CA > and client certificates and client key are derived automatically from > the value of `--certs-dir`. ## Using both URL and client parameters Most `cockroach` commands accept both a URL and client parameters. The information contained therein is combined in the order it appears in the command line. This combination is useful so that discrete command-line flags can override settings not otherwise set in the URL. ### Example override of the current database The `cockroach start` command prints out the following connection URL, which connects to the `defaultdb` database: ``` postgres://root@servername:26257/?sslmode=disable ``` To specify `mydb` as the current database using [`cockroach sql`](/docs/v26.4/cockroach-sql), run the following command: ``` cockroach sql \ --url "postgres://root@servername:26257/?sslmode=disable" \ --database mydb ``` This is equivalent to: ``` cockroach sql --url "postgres://root@servername:26257/mydb?sslmode=disable" ``` ## See also * [`cockroach` Commands Overview](/docs/v26.4/cockroach-commands) * [Create Security Certificates](/docs/v26.4/cockroach-cert) * [Secure a Cluster](/docs/v26.4/secure-a-cluster) * [Create and Manage Users](/docs/v26.4/security-reference/authorization#create-and-manage-users) # Connection Pooling Source: https://docs.cockroachlabs.com/docs/stable/connection-pooling This page has information on planning, configuring, and using connection pools when using drivers or frameworks with CockroachDB. > [!NOTE] > > In our sizing and production guidance, 1 vCPU is considered equivalent to 1 core in the underlying hardware platform. ## About connection pools A typical database operation consists of several steps. 1. The driver uses a configuration to start a connection to the database server. 2. A network socket is opened on the client that connects to the database server. 3. Data is read or written through the network socket. 4. The connection is closed down. 5. The network socket is closed down and its resources are freed. For simple database operations, these steps are not expensive, but as an application scales up, the performance of the application will suffer as each connection is created and destroyed. One pattern for improving performance is a connection pool, a group of already configured and established network connections between the client and database that can be reused for data operations within an application. Each time an application reads or writes data, it will request one of the connections in the pool. After the data operation completes, the connection is returned to the pool so other operations can use it. Connection pooling can be a enabled as a feature of the driver, a separate library used in conjunction with a driver, a feature of an application server, or a proxy server that acts as a gateway to the database server. Sizing a connection pool is critical to maximizing application performance. Too few connections and the application will be blocked, waiting for the connection pool to establish a new connection, or for an existing connection to become available. Conversely, a connection pool with too many connections actively executing a query at the same time can also result in high latency as the cluster cycles through every connection concurrently, decreasing efficiency as the cluster incurs a cost every time it context-switches through every query. For example, the time it takes for many threads to complete many queries in parallel is typically higher than that for a smaller number of threads scaled to the number of available vCPUs or IOPs. > [!TIP] > > To read more about connection pooling, see our [What is Connection Pooling, and Why Should You Care](https://www.cockroachlabs.com/blog/what-is-connection-pooling/) blog post. ## Recommended settings for connection pools These are Cockroach Labs recommendations for settings common to most connection pooling software. If your application has multiple workers, each worker should be configured based on the kinds of queries required for its workload. ### Set the maximum lifetime of connections The maximum lifetime of a connection should be set to between 5 and 30 minutes. CockroachDB Cloud clusters support 30 minutes as the maximum connection lifetime. When a node is shut down or restarted, client connections can be reset after 30 minutes, causing a disruption to applications. Cockroach Labs recommends starting with a 5 minute maximum connection lifetime and increasing the connection lifetime if there is an impact on tail latency, normally seen when there are large numbers of connections to a cluster. Setting the connection lifetime below 5 minutes is possible, but there is little benefit, and comes at a cost of increased CPU usage for clients and servers. The maximum connection lifetime changes the [rate of new connections per second](#monitor-new-connections) (i.e., average new connections per second = total connections / maximum connection age). Configure your connection pooling with [connection jitter](#avoid-spikes-in-new-connections) to prevent connection storms. ### Set the maximum lifetime of idle connections Set the maximum lifetime of idle connections to the same value as the [maximum lifetime of connections](#set-the-maximum-lifetime-of-connections). ### Set the maximum number of open connections The maximum number of open connections should be set to a value that is greater than the maximum number of concurrent queries that your application worker expects to make. Doing so minimizes the need to establish new connections. ### Set the maximum number of idle connections Set the maximum number of idle connections to the same value as the [maximum number of open connections](#set-the-maximum-number-of-open-connections). ## Optimize your connection pool Follow these additional recommendations optimize the performance of your connection pool software. ### Avoid spikes in new connections If possible configure your connection pool to avoid periodic spikes in new connections, also known as "thundering herds" or "connection storms." Most connection pools offer the ability to stagger their connection age through the use of a connection lifetime "jitter," where the wait time between new connections is randomized. Using a connection jitter of 10% of the maximum connection lifetime smooths out the rate of new connections to a cluster. For example, for a maximum connection lifetime of 1800 seconds (30 minutes), set the connection jitter to 500 seconds (3 minutes). ### Validate connections in a pool After a connection pool initializes connections to CockroachDB clusters, those connections can occasionally break. This could be due to changes in the cluster topology, or rolling upgrades and restarts, or network disruptions. Validating connections is typically handled automatically by the connection pool. For example, in HikariCP the connection is validated whenever you request a connection from the pool, and the [`keepaliveTime` property](https://github.com/brettwooldridge/HikariCP#frequently-used) allows you to configure an interval to periodically check if the connections in the pool are valid. Whatever connection pool you use, make sure connection validation is enabled when running your application. ## Size connection pools > [tab] Basic/Standard > > If your connection pool is properly configured, the total number of open connections to your cluster will typically be at least 100 times larger than the number of new connections per second to your cluster. > > Idle connections in CockroachDB do not consume many resources compared to PostgreSQL. Unlike PostgreSQL, which has a hard limit of 5000 connections, CockroachDB can safely support tens of thousands of connections. > > The [**SQL Connection** graph](/docs/cockroachcloud/metrics-sql#sql-connections) shows how many new connections are being created each second. The [**Open SQL Sessions** graph](/docs/cockroachcloud/metrics-sql#open-sql-sessions) shows the total number of SQL client connections across the cluster. To determine if your connection pool is correctly configured use the metrics from these graphs in the following formula: > > **SQL Connection Attempts \< SQL Open Sessions/100** > > That is, divide the number of open SQL sessions by 100. This result should be less than the number of new SQL connections per second. > > Configure the minimum number of connections to equal to the maximum number of connections, creating a fixed pool size. > > Configure the maximum connection lifetime to 30 minutes. > > Multi-region Basic and Standard clusters have the same recommendations as single-region clusters. > > Cockroach Labs strongly recommends that your application instance run in the same region as your CockroachDB cluster. > [tab] Advanced > > If your connection pool is properly configured, the total number of open connections to your cluster will typically be at least 100 times larger than the number of new connections per second to your cluster. > > Idle connections in CockroachDB do not consume many resources compared to PostgreSQL. Unlike PostgreSQL, which has a hard limit of 5000 connections, CockroachDB can safely support tens of thousands of connections. > > Use the following formula as a starting point to size the connection pool: > > **active connections = (number of cores \* 4)** > > If you have a large number of services connecting to the same cluster, make sure the number of [concurrent active connections](#monitor-active-connections) across all the services does not exceed this recommendation. If each service has its own connection pool, ensure the total number of concurrent active connections across all services stays within this limit. > > For multi-region clusters, create a connection pool per region, and apply the same active connection limits for each region in your cluster. For example, if you have 3 regions in your cluster, and each region has 12 vCPUs, the concurrent active connection limit **per region** is 48 (12 \[processor cores] \* 4). > > > [!NOTE] > > > > [Connection pool sizes](#set-the-maximum-number-of-open-connections) can be much larger than the active connections limit, since most connections will be idle and have almost no overhead. > > To control the maximum number of non-superuser ([`root`](/docs/v26.4/security-reference/authorization) user or other [`admin` role](/docs/v26.4/security-reference/authorization#admin-role)) connections a [gateway node](/docs/v26.4/architecture/sql-layer) can have open at one time, use the `server.max_connections_per_gateway` [cluster setting](/docs/v26.4/cluster-settings). If a new non-superuser connection would exceed this limit, the error message `"sorry, too many clients already"` is returned, along with error code `53300`. > > Cockroach Labs strongly recommends that your application instance run in the same region as your CockroachDB cluster. > [tab] self-hosted > > If your connection pool is properly configured, the total number of open connections to your cluster will typically be at least 100 times larger than the number of new connections per second to your cluster. > > Idle connections in CockroachDB do not consume many resources compared to PostgreSQL. Unlike PostgreSQL, which has a hard limit of 5000 connections, CockroachDB can safely support tens of thousands of connections. > > Use the following formula as a starting point to size the connection pool: > > **active connections = (number of cores \* 4)** > > If you have a large number of services connecting to the same cluster, make sure the number of [concurrent active connections](#monitor-active-connections) across all the services does not exceed this recommendation. If each service has its own connection pool, ensure the total number of concurrent active connections across all services stays within this limit. > > For multi-region clusters, create a connection pool per region, and apply the same active connection limits for each region in your cluster. For example, if you have 3 regions in your cluster, and each region has 12 vCPUs, the concurrent active connection limit **per region** is 48 (12 \[processor cores] \* 4). > > > [!NOTE] > > > > [Connection pool sizes](#set-the-maximum-number-of-open-connections) can be much larger than the active connections limit, since most connections will be idle and have almost no overhead. > > To control the maximum number of non-superuser ([`root`](/docs/v26.4/security-reference/authorization#root-user) user or other [`admin` role](/docs/v26.4/security-reference/authorization#admin-role)) connections a [gateway node](/docs/v26.4/architecture/sql-layer) can have open at one time, use the `server.max_connections_per_gateway` [cluster setting](/docs/v26.4/cluster-settings). If a new non-superuser connection would exceed this limit, the error message `"sorry, too many clients already"` is returned, along with error code `53300`. > > Cockroach Labs strongly recommends that your application instance run in the same region as your CockroachDB cluster. ## Monitor SQL connections > [tab] Basic/Standard > > To validate that your connection pool is correctly configured, monitor the SQL connection metrics and graphs on your cluster. > > ### Monitor new connections > > The [**SQL Connections** graph](/docs/cockroachcloud/metrics-sql#sql-connections) shows the number of new SQL connections per second. > > A misconfigured connection pool will result in most database operations requiring a new connection to be established, which will increase query latency. > > ### Monitor active connections > > The [**Open SQL Sessions** graph](/docs/cockroachcloud/metrics-sql#open-sql-sessions) shows the number of open connections on your cluster. > > If your connection pool is properly configured, the total number of open connections to your cluster should be at least 100 times larger than the number of new connections per second to your cluster. > [tab] Advanced > > To validate that your connection pool is correctly configured, monitor the SQL connection metrics and graphs on your cluster. > > ### Monitor new connections > > The [`sql.new_conns` metric](/docs/v26.4/metrics#available-metrics) and [**SQL Connection Rate** graph](/docs/v26.4/ui-sql-dashboard#sql-connection-rate) expose the number of new SQL connections per second. > > A misconfigured connection pool will result in most database operations requiring a new connection to be established, which will increase query latency. > > ### Monitor active connections > > The [`sql.conns` metric](/docs/v26.4/metrics#available-metrics) and [**Open SQL Sessions** graph](/docs/v26.4/ui-sql-dashboard#open-sql-sessions) show the number of open connections on your cluster or node. > > The [`sql.statements.active` metric](/docs/v26.4/metrics#available-metrics) and [**Active SQL Statements** graph](/docs/v26.4/ui-sql-dashboard#active-sql-statements) show the number of **active** connections on your cluster or node. A connection is "active" when it is actively executing a query. > > Using the following formula: > > **active connections = (number of cores \* 4)** > > If the number of concurrent active connections exceeds 4 times the number of cores in your cluster, your application is likely not achieving maximum throughput. You should reduce the concurrent workload across your applications, or scale the cluster by adding more nodes or cores per node. Reducing the number of active connections may increase overall throughput, possibly at the expense of increased tail latency for your queries. > > If your connection pool is properly configured, the total number of open connections to your cluster should be at least 100 times larger than the number of new connections per second to your cluster. > [tab] self-hosted > > To validate that your connection pool is correctly configured, monitor the SQL connection metrics and graphs on your cluster. > > ### Monitor new connections > > The [`sql.new_conns` metric](/docs/v26.4/metrics#available-metrics) and [**SQL Connection Rate** graph](/docs/v26.4/ui-sql-dashboard#sql-connection-rate) expose the number of new SQL connections per second. > > A misconfigured connection pool will result in most database operations requiring a new connection to be established, which will increase query latency. > > ### Monitor active connections > > The [`sql.conns` metric](/docs/v26.4/metrics#available-metrics) and [**Open SQL Sessions** graph](/docs/v26.4/ui-sql-dashboard#open-sql-sessions) show the number of open connections on your cluster or node. > > The [`sql.statements.active` metric](/docs/v26.4/metrics#available-metrics) and [**Active SQL Statements** graph](/docs/v26.4/ui-sql-dashboard#active-sql-statements) show the number of **active** connections on your cluster or node. A connection is "active" when it is actively executing a query. > > Using the following formula: > > **active connections = (number of cores \* 4)** > > If the number of concurrent active connections exceeds 4 times the number of cores in your cluster, your application is likely not achieving maximum throughput. You should reduce the concurrent workload across your applications, or scale the cluster by adding more nodes or cores per node. Reducing the number of active connections may increase overall throughput, possibly at the expense of increased tail latency for your queries. > > If your connection pool is properly configured, the total number of open connections to your cluster should be at least 100 times larger than the number of new connections per second to your cluster. ## Serverless functions > [!NOTE] > > "Serverless" refers to stateless, programmatic functions deployed in a cloud environment that provides an execution framework to provision resources dynamically, such as Amazon Lambda functions. If your application uses serverless functions to connect to CockroachDB, use a connection pool if you plan to invoke functions frequently. To ensure that the connection pool is reused across invocations of the same function instance, initialize the connection pool variable outside the scope of the serverless function definition. Set the maximum connection pool size to 1, unless your function is multi-threaded and establishes multiple concurrent requests to your database within a single function instance. ## Example > [tab] Java (Hikari/JDBC) > > In this example, a Java application similar to the [basic JDBC example](/docs/v26.4/build-a-java-app-with-cockroachdb) uses the [PostgreSQL JDBC driver](https://jdbc.postgresql.org/) and [HikariCP](https://github.com/brettwooldridge/HikariCP) as the connection pool layer to connect to a CockroachDB cluster. The database is being run on 10 cores across the cluster. > > Using the connection pool formula above: > > **connections = (10 \[processor cores] \* 4)** > > The connection pool size should be 40. > > The maximum lifetime of a connection is set to 300000 milliseconds, or 5 minutes. > > ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > HikariConfig config = new HikariConfig(); > config.setJdbcUrl("jdbc:postgresql://localhost:26257/bank"); > config.setUsername("maxroach"); > config.setPassword("password"); > config.addDataSourceProperty("ssl", "true"); > config.addDataSourceProperty("sslmode", "require"); > config.addDataSourceProperty("reWriteBatchedInserts", "true"); > config.setAutoCommit(false); > config.setMaximumPoolSize(40); > config.setMaxLifetime(300000); > config.setKeepaliveTime(150000); > > HikariDataSource ds = new HikariDataSource(config); > > Connection conn = ds.getConnection(); > ``` > [tab] Go (pgxpool) > > In this example, a Go application similar to the [basic pgx example](/docs/v26.4/build-a-go-app-with-cockroachdb) uses the [pgxpool library](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool) to create a connection pool on a CockroachDB cluster. The database is being run on 10 cores across the cluster. > > Using the connection pool formula above: > > **connections = (10 \[processor cores] \* 4)** > > The connection pool size should be 40, and is set using the `pool_max_conns` query parameter. > > The `pool_max_conn_lifetime` query parameter sets the maximum age of a connection to 300 seconds, or 5 minutes. > > The `pool_max_conn_lifetime_jitter` query parameter sets the connection jitter to 30 seconds, or 10% of the maximum connection age. > > ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > // Set connection pool configuration, with maximum connection pool size. > config, err := pgxpool.ParseConfig("postgres://max:roach@127.0.0.1:26257/bank?sslmode=require&pool_max_conns=40&pool_max_conn_lifetime=300s&pool_max_conn_lifetime_jitter=30s") > if err != nil { > log.Fatal("error configuring the database: ", err) > } > > // Create a connection pool to the "bank" database. > dbpool, err := pgxpool.ConnectConfig(context.Background(), config) > if err != nil { > log.Fatal("error connecting to the database: ", err) > } > defer dbpool.Close() > ``` > > For a full list of connection pool configuration parameters for pgxpool, see [the pgxpool documentation](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool#Config). ## Known limitations * When a node has both a high number of client connections and running queries, the node may crash due to memory exhaustion. This is due to CockroachDB not accurately limiting the number of clients and queries based on the amount of available RAM on the node. To prevent memory exhaustion, monitor each node's memory usage and ensure there is some margin between maximum CockroachDB memory usage and available system RAM. For more details about memory usage in CockroachDB, see [this blog post](https://www.cockroachlabs.com/blog/memory-usage-cockroachdb/). # Advanced Public Key Infrastructure (PKI) Certificate Scenarios Source: https://docs.cockroachlabs.com/docs/stable/create-security-certificates-custom-ca This document discusses the use of advanced [Public Key Infrastructure (PKI)](/docs/v26.4/security-reference/transport-layer-security) systems and certificates issued by them with CockroachDB. security certificates with CockroachDB. PKI certificates are used in CockroachDB for TLS encryption and for node and client authentication. | Approach | Use case description | | - | - | | [UI certificate and key](#accessing-the-db-console-for-a-secure-cluster) | When you want to access the DB Console for a secure cluster and avoid clicking through a warning message to get to the UI. | | [Split-node certificate](#split-node-certificates) | When your organizational CA requires you to have separate certificates for the node's incoming connections (from SQL and DB Console clients, and from other CockroachDB nodes) and for outgoing connections to other CockroachDB nodes. | | [Split-CA certificates](#split-ca-certificates) | When you have multiple CockroachDB clusters and need to restrict access to clients from accessing the other cluster. | ## Accessing the DB Console for a secure cluster On [accessing the DB Console](/docs/v26.4/ui-overview#db-console-access) for a secure cluster, your web browser will consider the CockroachDB-issued certificate invalid, because the browser hasn't been configured to trust the CA that issued the certificate. For secure clusters, you can avoid getting the warning message by using a certificate issued by a public CA whose certificates are trusted by browsers, in addition to the CockroachDB-created certificates. 1. Request a certificate from a public CA (for example, [Let's Encrypt](https://letsencrypt.org/)). The certificate must have the IP addresses and DNS names used to reach the DB Console listed in the `Subject Alternative Name` field. 2. Rename the certificate and key files to `ui.crt` and `ui.key`. 3. Add the `ui.crt` and `ui.key` files to the [trust store](/docs/v26.4/security-reference/transport-layer-security#trust-store). `ui.key` must meet the [permission requirements check](/docs/v26.4/cockroach-cert#key-file-permissions) on macOS, Linux, and other UNIX-like systems. If your cluster is deployed using containers, update the containers to include the new certificate and key. 4. The cockroach process reads certificates only when the process starts. * In a manually-deployed cluster, load the `ui.crt` certificate without restarting the node by issuing a `SIGHUP` signal to the cockroach process: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} pkill -SIGHUP -x cockroach ``` The `SIGHUP` signal must be sent by the same user running the process or by a user with adequate privileges to send signals to processes owned by another user, such as a user with `sudo` access. * In a cluster deployed using the [Public operator](/docs/v26.4/deploy-cockroachdb-with-kubernetes), there is no way to send a `SIGHUP` signal to the individual `cockroach` process on each cluster node. Instead, perform a rolling restart of the cluster's pods. ### Node key and certificates A node must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate issued by the public CA or your organizational CA. | | `node.crt` | Server certificate created using the `cockroach cert` command. `node.crt` must have `CN=node` and the list of IP addresses and DNS names listed in `Subject Alternative Name` field. Must be signed by `ca.crt`. | | `node.key` | Server key created using the `cockroach cert` command. | | `ui.crt` | UI certificate signed by the public CA. `ui.crt` must have the IP addresses and DNS names used to reach the DB Console listed in `Subject Alternative Name`. | | `ui.key` | UI key corresponding to `ui.crt`. | ### Client key and certificates A client must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate issued by the public CA or your organizational CA. | | `client. [!CAUTION] > > We do not recommend you use split CA certificates unless your organizational security practices mandate you to do so. If you need to use separate CAs to sign node certificates and client certificates, then you need two CAs and their respective certificates and keys: `ca.crt` and `ca-client.crt`. ### Node key and certificates A node must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate to verify node certificates. | | `ca-client.crt` | CA certificate to verify client certificates. | | `node.crt` | Server certificate used when a node receives incoming connections from clients and other nodes. All IP addresses and DNS names for the node must be listed in `Subject Alternative Name`. Must be signed by `ca.crt`. | | `node.key` | Server key corresponding to `node.crt`. | | `client.node.crt` | Client certificate when making connections to other nodes. This certificate must be signed using `ca-client.crt` Must have `CN=node`. | | `client.node.key` | Client key corresponding to `client.node.crt`. | Optionally, if you have a certificate issued by a public CA to securely access the DB Console, you need to place the certificate and key (`ui.crt` and `ui.key` respectively) in the directory specified by the `--certs-dir` flag. ### Client key and certificates A client must have the following files with file names as specified in the table: | File name | File usage | | - | - | | `ca.crt` | CA certificate. | | `client. SHOW CLUSTER SETTING security.ocsp.mode; ``` ``` security.ocsp.mode ---------------------- off (1 row) Server Execution Time: 56µs Network Latency: 181µs ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SET CLUSTER SETTING security.ocsp.mode = lax; ``` For production clusters, you might want to set the setting to `strict`. > [!NOTE] > > In the `strict` mode, all certificates are presumed to be invalid if the OCSP server is not reachable. Setting the cluster setting `security.ocsp.mode` to `strict` will lock you out of your CockroachDB database if your OCSP server goes down. ## See also * [Public Key Infrastructure (PKI) and Transport Layer Security (TLS)](/docs/v26.4/security-reference/transport-layer-security) * [Use the CockroachDB CLI to provision a development cluster](/docs/v26.4/manage-certs-cli). * [Manage PKI certificates for a CockroachDB deployment with HashiCorp Vault](/docs/v26.4/manage-certs-vault). * [Manual Deployment](/docs/v26.4/manual-deployment): Learn about starting a multi-node secure cluster and accessing it from a client. * [Start a Node](/docs/v26.4/cockroach-start): Learn more about the flags you pass when adding a node to a secure cluster * [Client Connection Parameters](/docs/v26.4/connection-parameters) # Create Security Certificates using OpenSSL Source: https://docs.cockroachlabs.com/docs/stable/create-security-certificates-openssl This tutorial shows how to provision a [public key infrastructure (PKI) certificate authority (CA)](/docs/v26.4/security-reference/transport-layer-security) for a CockroachDB self-hosted cluster deployed in Google Cloud Platform (GCP). See also: * [Public Key Infrastructure (PKI) and Transport Layer Security (TLS)](/docs/v26.4/security-reference/transport-layer-security) * [Use the CockroachDB CLI to provision a development cluster](/docs/v26.4/manage-certs-cli). * [Manage PKI certificates for a CockroachDB deployment with HashiCorp Vault](/docs/v26.4/manage-certs-vault). To create these certificates and keys, use the `cockroach cert` [commands](/docs/v26.4/cockroach-commands) with the appropriate subcommands and flags, use [`openssl` commands](https://wiki.openssl.org/index.php/), or use a [custom CA](/docs/v26.4/create-security-certificates-custom-ca) (for example, a public CA or your organizational CA). If you manage your own Certificate Authority (CA) infrastructure, CockroachDB supports mapping between the Subject field of your [X.509 certificates](https://en.wikipedia.org/wiki/X.509) and SQL [roles](/docs/v26.4/security-reference/authorization#roles). For more information, see [Certificate-based authentication using multiple values from the X.509 Subject field](/docs/v26.4/certificate-based-authentication-using-the-x509-subject-field). ## Subcommands | Subcommand | Usage | | - | - | | [`openssl genrsa`](https://www.openssl.org/docs/manmaster/man1/genrsa.html) | Create an RSA private key. | | [`openssl req`](https://www.openssl.org/docs/manmaster/man1/req.html) | Create CA certificate and CSRs (certificate signing requests). | | [`openssl ca`](https://www.openssl.org/docs/manmaster/man1/ca.html) | Create node and client certificates using the CSRs. | ## Configuration files To use [`openssl req`](https://www.openssl.org/docs/manmaster/man1/req.html) and [`openssl ca`](https://www.openssl.org/docs/manmaster/man1/ca.html) subcommands, you need the following configuration files: | File name pattern | File usage | | - | - | | `ca.cnf` | CA configuration file | | `node.cnf` | Server configuration file | | `client.cnf` | Client configuration file | ## Certificate directory To create node and client certificates using the OpenSSL commands, you need access to a local copy of the CA certificate and key. We recommend creating all certificates (node, client, and CA certificates), and node and client keys in one place and then distributing them appropriately. Store the CA key somewhere safe and keep a backup; if you lose it, you will not be able to add new nodes or clients to your cluster. ## Required keys and certificates Use the [`openssl genrsa`](https://www.openssl.org/docs/manmaster/man1/genrsa.html) and [`openssl req`](https://www.openssl.org/docs/manmaster/man1/req.html) subcommands to create all certificates, and node and client keys in a single directory, with the files named as follows: ### Node key and certificates | File name pattern | File usage | | - | - | | `ca.crt` | CA certificate | | `node.crt` | Server certificate | | `node.key` | Key for server certificate | ### Client key and certificates | File name pattern | File usage | | - | - | | `ca.crt` | CA certificate. | | `client. [!CAUTION] > > The `keyUsage` and `extendedkeyUsage` parameters are vital for CockroachDB functions. You can modify or omit other parameters as per your preferred OpenSSL configuration and you can add additional usages, but do not omit `keyUsage` and `extendedkeyUsage` parameters or remove the listed usages. 1. Create the CA key using the [`openssl genrsa`](https://www.openssl.org/docs/manmaster/man1/genrsa.html) command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl genrsa -out my-safe-directory/ca.key 2048 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ chmod 400 my-safe-directory/ca.key ``` 2. Create the CA certificate using the [`openssl req`](https://www.openssl.org/docs/manmaster/man1/req.html) command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl req \ -new \ -x509 \ -config ca.cnf \ -key my-safe-directory/ca.key \ -out certs/ca.crt \ -days 365 \ -batch ``` 3. Reset database and index files: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ rm -f index.txt serial.txt ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ touch index.txt ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo '01' > serial.txt ``` ### Step 2. Create the certificate and key pairs for nodes In the following steps, replace the placeholder text in the code with the actual username and node address. 1. Create the `node.cnf` file for the first node and copy the following configuration into it: ``` # OpenSSL node configuration file [ req ] prompt=no distinguished_name = distinguished_name req_extensions = extensions [ distinguished_name ] organizationName = Cockroach [ extensions ] subjectAltName = critical,DNS: ``` > [!CAUTION] > > The `subjectAltName` parameter is vital for CockroachDB functions. You can modify or omit other parameters as per your preferred OpenSSL configuration, but do not omit the `subjectAltName` parameter. 1. Create the key for the first node using the [`openssl genrsa`](https://www.openssl.org/docs/manmaster/man1/genrsa.html) command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl genrsa -out certs/node.key 2048 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ chmod 400 certs/node.key ``` 2. Create the CSR for the first node using the [`openssl req`](https://www.openssl.org/docs/manmaster/man1/req.html) command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl req \ -new \ -config node.cnf \ -key certs/node.key \ -out node.csr \ -batch ``` 3. Sign the node CSR to create the node certificate for the first node using the [`openssl ca`](https://www.openssl.org/docs/manmaster/man1/ca.html) command. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl ca \ -config ca.cnf \ -keyfile my-safe-directory/ca.key \ -cert certs/ca.crt \ -policy signing_policy \ -extensions signing_node_req \ -out certs/node.crt \ -outdir certs/ \ -in node.csr \ -batch ``` 4. Verify the values in the `Subject Alternative Name` field in the certificate: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl x509 -in certs/node.crt -text | grep "X509v3 Subject Alternative Name" -A 1 ``` Sample output: ``` X509v3 Subject Alternative Name: critical DNS:localhost, DNS:node.example.io, IP Address:127.0.0.1 ``` ### Step 3. Create the certificate and key pair for the first user In the following steps, replace the placeholder text in the code with the actual username. 1. Create the `client.cnf` file for the first user and copy the following configuration into it: ``` [ req ] prompt=no distinguished_name = distinguished_name req_extensions = extensions [ distinguished_name ] organizationName = Cockroach commonName = [ extensions ] subjectAltName = DNS:root ``` > [!CAUTION] > > The `commonName` and `subjectAltName` parameters are vital for CockroachDB functions. You can modify or omit other parameters as per your preferred OpenSSL configuration, but do not omit the `commonName` parameter or modify the `subjectAltName` parameter. 1. Create the key for the first client using the [`openssl genrsa`](https://www.openssl.org/docs/manmaster/man1/genrsa.html) command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl genrsa -out certs/client. create user ; ``` 4. Exit the SQL shell: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ### Step 5. Create the certificate and key pair for a client In the following steps, replace the placeholder text in the code with the actual username. 1. Edit the `client.cnf` file for the client and copy the following configuration into it: ``` [ req ] prompt=no distinguished_name = distinguished_name [ distinguished_name ] organizationName = Cockroach commonName = ``` 2. Create the key for the first client using the [`openssl genrsa`](https://www.openssl.org/docs/manmaster/man1/genrsa.html) command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl genrsa -out certs/client. [!TIP] > > For a practical guide on how CockroachDB uses Raft to replicate, distribute, and rebalance data, refer to the [CockroachDB Resilience demo](/docs/v26.4/demo-cockroachdb-resilience). ## High availability * [**Multi-active availability**](/docs/v26.4/multi-active-availability): CockroachDB's built-in [Raft replication](/docs/v26.4/architecture/replication-layer) stores data safely and consistently on multiple nodes to ensure no downtime even during a temporary node outage. [Replication controls](/docs/v26.4/configure-replication-zones) allow you to configure the number and location of [replicas](/docs/v26.4/architecture/glossary#replica) to suit a deployment. * For more detail on planning for single-region or multi-region recovery, refer to [Single-region survivability planning](/docs/v26.4/disaster-recovery-planning#single-region-survivability-planning) or [Multi-region survivability planning](/docs/v26.4/disaster-recovery-planning#multi-region-survivability-planning). * [**Advanced fault tolerance**](/docs/v26.4/demo-cockroachdb-resilience): Capabilities built in to CockroachDB to perform routine maintenance operations with minimal impact to foreground performance. For example, [online schema changes](/docs/v26.4/online-schema-changes), [write-ahead log failover](/docs/v26.4/cockroach-start#write-ahead-log-wal-failover), and [Leader leases](/docs/v26.4/architecture/replication-layer#leader-leases). * [**Logical data replication (LDR)**](/docs/v26.4/logical-data-replication-overview) (Preview): A cross-cluster replication tool between active CockroachDB clusters, which supports a range of topologies. LDR provides eventually consistent, table-level replication between the clusters. Individually, each active cluster uses CockroachDB multi-active availability to achieve low, single-region write latency with transactionally consistent writes using Raft replication. ### Choose an HA strategy | | Single-region replication (synchronous) | Multi-region replication (synchronous) | Logical data replication (asynchronous) | | - | - | - | - | | **RPO** | 0 seconds | 0 seconds | Immediate mode 0.5 seconds | | **RTO** | Zero RTO Potential increased latency for 1-9 seconds | Zero RTO Potential increased latency for 1-9 seconds | Zero RTO Application traffic failover time | | **Write latency** | Region-local write latency p50 latency \< 5ms (for multiple availability zones in us-east1) | Cross-region write latency p50 latency > 50ms (for a multi-region cluster in us-east1, us-east-2, us-west-1) | Region-local latency depending on design p50 latency \< 5ms (for multiple availability zones in us-east1) | | **Recovery** | Automatic | Automatic | Semi-automatic | | **Fault tolerance** | Zero RPO node, availability zone failures within a cluster | Zero RPO node, availability zone failures, region failures within a cluster | Zero RPO node, availability zone within a cluster, region failures with loss up to RPO in a two-region (or two datacenter) setup | | **Minimum regions to achieve fault tolerance** | 1 | 3 | 2 | For details on designing your cluster topology for HA with replication, refer to the [Disaster Recovery Planning](/docs/v26.4/disaster-recovery-planning#hardware-failure) page. ## Disaster recovery * [**Backup and point-in-time restore**](/docs/v26.4/take-backups-with-revision-history-and-restore-from-a-point-in-time): Point-in-time backup and restore allows you to roll back to a specific point in time. Multiple supported [cloud storage](/docs/v26.4/use-cloud-storage) providers means that you can store backups in your chosen provider. [Incremental backups](/docs/v26.4/take-full-and-incremental-backups) allow you to configure backup frequency for lower [RPO](/docs/v26.4/disaster-recovery-overview). * [**Physical cluster replication (PCR)**](/docs/v26.4/physical-cluster-replication-overview): A cross-cluster replication tool between an active primary CockroachDB cluster and a passive standby CockroachDB cluster. PCR provides transactionally consistent full-cluster replication. ### Choose a DR strategy CockroachDB is designed to recover automatically; however, building backups or PCR into your DR plan protects against unforeseen incidents. | | Point-in-time backup & restore | Physical cluster replication (asynchronous) | | - | - | - | | **RPO** | >=5 minutes | 10s of seconds | | **RTO** | Minutes to hours, depending on data size and number of nodes | Seconds to minutes, depending on cluster size, and time of failover | | **Write latency** | No impact | No impact | | **Recovery** | Manual restore | Manual failover | | **Fault tolerance** | Not applicable | Zero RPO node, availability zone within a cluster, region failures with loss up to RPO in a two-region (or two-datacenter) setup | | **Minimum regions to achieve fault tolerance** | 1 | 2 | ## See also * [Architecture Overview](/docs/v26.4/architecture/overview) * [Set Up Logical Data Replication](/docs/v26.4/set-up-logical-data-replication) * [Set Up Physical Cluster Replication](/docs/v26.4/set-up-physical-cluster-replication) * [Physical Cluster Replication Technical Overview](/docs/v26.4/physical-cluster-replication-technical-overview) * [Backup Architecture](/docs/v26.4/backup-architecture) * [Backup and Restore Overview](/docs/v26.4/backup-and-restore-overview) * [Managed Backups](/docs/cockroachcloud/managed-backups) # CockroachDB Resilience Demo Source: https://docs.cockroachlabs.com/docs/stable/demo-cockroachdb-resilience This page describes how to perform a hands-on demonstration of CockroachDB's fault-tolerant design allowing services to remain available during a failure and recovery. ## Run a guided demo in CockroachDB Cloud CockroachDB Cloud Advanced includes a built-in fault tolerance demo in the Cloud Console that automatically runs a sample workload and executes a controlled availability zone failure on your cluster, showing real-time metrics of query latency and failure rate during the outage and recovery. The CockroachDB Cloud fault tolerance demo is in [Preview](/docs/releases/cockroachdb-feature-availability). The following prerequisites are needed to run the fault tolerance demo: * You must have [CockroachDB Advanced cluster](/docs/cockroachcloud/create-an-advanced-cluster) with at least three nodes. * All nodes must be healthy. * The cluster's CPU utilization must be below 30%. * The cluster must not currently be in a locked state as a result of maintenance such as scaling. Clusters that were recently created may be locked intermittently while post-provisioning setup completes. Monitor your cluster's status in the Cloud Console to make sure it is not in a maintenance state. * You must have the [Cluster Operator](/docs/cockroachcloud/authorization#cluster-operator) and/or [Cluster Admin](/docs/cockroachcloud/authorization#cluster-admin) role assigned to start the demo. * Another fault tolerance demo must not currently be running. In total, the fault tolerance demo takes approximately 10 to 15 minutes to complete. The demo creates a temporary database and demo workload on your cluster, then cleans up after the demo is complete. If the demo becomes stuck, the system will automatically force a full cleanup after 30 minutes. You do not need to contact support before this window has elapsed. The fault tolerance demo is not recommended to be run on a production cluster. The demo temporarily blocks network communication to all nodes in one availability zone. This disruption is real, and may affect cluster performance during the outage window. Instead, use a dedicated test or staging cluster for the fault tolerance demo. To run the fault tolerance demo, open the Cloud Console and navigate to the **Overview** page, then select **Actions > Fault tolerance demo**. ### Known limitations The following known limitations apply to the fault tolerance demo in CockroachDB Cloud: * QPS may briefly appear to drop to zero on the chart during or after the disruption phase. This occurs because metrics from the nodes in the disrupted availability zone are temporarily unavailable during the network block, it does not reflect actual cluster behavior. The unaffected nodes continue serving traffic normally. * If you cancel the fault tolerance demo and immediately try to start a new one, you may encounter an error. Wait a few minutes before starting again. * Clean-up of the temporary workload and database may continue for a few minutes after the demo ends. Refresh the Console page if the message does not clear after a few minutes. ## Run a manual demo on a local machine This guide walks you through a simple demonstration of CockroachDB's resilience on a local cluster deployment. Starting with a 6-node local cluster with the default 3-way replication, you will perform the following steps: 1. Run a sample workload. 2. Terminate a node to simulate failure. 3. Observe the cluster continuing to serve query traffic uninterrupted during the failure state. 4. Observe the cluster repair itself by re-replicating missing data to other nodes. 5. Prepare the cluster for 2 simultaneous node failures by increasing to 5-way replication. ^.6. Take two nodes offline at the same time, and again observe how the cluster continues uninterrupted. ### Before you begin Make sure you have already [installed CockroachDB](/docs/v26.4/install-cockroachdb-mac). ### Step 1. Start a 6-node cluster 1. In separate terminal windows, use the [`cockroach start`](/docs/v26.4/cockroach-start) command to start six nodes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node1 \ --listen-addr=localhost:26257 \ --http-addr=localhost:8080 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node2 \ --listen-addr=localhost:26258 \ --http-addr=localhost:8081 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node3 \ --listen-addr=localhost:26259 \ --http-addr=localhost:8082 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node4 \ --listen-addr=localhost:26260 \ --http-addr=localhost:8083 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node5 \ --listen-addr=localhost:26261 \ --http-addr=localhost:8084 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node6 \ --listen-addr=localhost:26262 \ --http-addr=localhost:8085 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` 2. Use the [`cockroach init`](/docs/v26.4/cockroach-init) command to perform a one-time initialization of the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --insecure --host=localhost:26257 ``` ### Step 2. Set up load balancing In this tutorial, you run a sample workload to simulate multiple client connections. Each node is an equally suitable SQL gateway for the load, but it's always recommended to [spread requests evenly across nodes](/docs/v26.4/recommended-production-settings#load-balancing). This section shows how to set up the open-source [HAProxy](http://www.haproxy.org/) load balancer. 1. Install HAProxy. > [tab] Mac > > If you're on a Mac and use Homebrew, run: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ brew install haproxy > ``` > [tab] Linux > > If you're using Linux and use apt-get, run: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ sudo apt-get install haproxy > ``` 2. Run the [`cockroach gen haproxy`](/docs/v26.4/cockroach-gen) command, specifying the port of any node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach gen haproxy --insecure --host=localhost --port=26257 ``` This command generates an `haproxy.cfg` file automatically configured to work with the nodes of your running cluster. 3. In `haproxy.cfg`, change `bind :26257` to `bind :26000`. This changes the port on which HAProxy accepts requests to a port that is not already in use by a node. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} sed -i.saved 's/^ bind :26257/ bind :26000/' haproxy.cfg ``` 4. Start HAProxy, with the `-f` flag pointing to the `haproxy.cfg` file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ haproxy -f haproxy.cfg & ``` ### Step 3. Run a sample workload Use the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to run CockroachDB's built-in version of the YCSB benchmark, simulating multiple client connections, each performing mixed read/write operations. 1. Load the initial `ycsb` schema and data, pointing it at HAProxy's port: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload init ycsb --splits=50 'postgresql://root@localhost:26000?sslmode=disable' ``` The `--splits` flag tells the workload to manually split ranges a number of times. This is not something you'd normally do, but for the purpose of this tutorial, it makes it easier to visualize the movement of data in the cluster. 2. Run the `ycsb` workload, pointing it at HAProxy's port: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload run ycsb \ --duration=20m \ --concurrency=3 \ --max-rate=1000 \ --tolerate-errors \ 'postgresql://root@localhost:26000?sslmode=disable' ``` This command initiates 3 concurrent client workloads for 20 minutes, but limits the total load to 1000 operations per second (since you're running everything on a single machine). You'll see per-operation statistics print to standard output every second: ``` _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms) 1.0s 0 902.8 930.9 1.1 2.1 4.1 62.9 read 1.0s 0 46.5 48.0 3.4 4.7 6.0 6.0 update 2.0s 0 923.3 926.9 1.0 2.9 5.5 8.9 read 2.0s 0 38.0 43.0 3.0 6.0 7.6 7.6 update 3.0s 0 901.1 918.3 1.1 2.5 5.0 6.6 read 3.0s 0 55.0 47.0 3.4 7.9 9.4 11.5 update 4.0s 0 948.9 926.0 1.0 1.6 2.6 5.0 read 4.0s 0 46.0 46.7 3.1 5.2 16.8 16.8 update 5.0s 0 932.0 927.2 1.1 1.8 2.9 13.6 read 5.0s 0 56.0 48.6 3.0 4.2 5.2 5.5 update ... ``` After the specified duration (20 minutes in this case), the workload will stop and you'll see totals printed to standard output. ### Step 4. Check the workload Initially, the workload creates a new database called `ycsb`, creates the table `public.usertable` in that database, and inserts rows into the table. Soon, the load generator starts executing approximately 95% reads and 5% writes. 1. Go to the DB Console at [http://localhost:8080](http://localhost:8080). 2. To check the SQL queries getting executed, click **Metrics** on the left, and hover over the **SQL Statements** graph at the top: ![DB Console SQL Statements](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-1.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=25cac5094b80a7945b85b19f3838b354) 3. To check the client connections from the load generator, select the **SQL** dashboard and hover over the **Open SQL Sessions** graph: ![DB Console Open Sessions](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-2.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=cb09d7373fec16199bdb763a78172975) You'll notice 3 client connections from the load generator. If you want to check that HAProxy balanced each connection to a different node, you can change the **Graph** dropdown from **Cluster** to specific nodes. 4. To see more details about the `ycsb` database and the `public.usertable` table, click **Databases** in the upper left and click **ycsb**: ![DB Console Databases](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-3.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=865c17d6a057d738bedacd57676f7f07) You can also view the schema and other table details of `public.usertable` by clicking the table name: ![DB Console usertable](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-4.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=309851178cd72b8f0d9fad005c9f01e1) 5. By default, CockroachDB replicates all data 3 times and balances it across all nodes. To see this balance, click **Overview** and check the replica count across all nodes: ![DB Console Overview](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-6.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=50f16f55671dce13e2f7222d7d40199e) ### Step 5. Simulate a single node failure When a node fails, the cluster waits for the node to remain offline for 5 minutes by default before considering it dead, at which point the cluster automatically repairs itself by re-replicating any of the replicas on the down nodes to other available nodes. 1. In a new terminal, [edit the default replication zone](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to reduce the amount of time the cluster waits before considering a node dead to the minimum allowed of 1 minute and 15 seconds: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost:26000 \ --execute="SET CLUSTER SETTING server.time_until_store_dead = '1m15s';" ``` 2. Get the process IDs of the nodes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ps -ef | grep cockroach | grep -v grep ``` ``` 503 53645 1 0 10:18AM ttys013 0:44.80 cockroach start --insecure --store=fault-node1 --listen-addr=localhost:26257 --http-addr=localhost:8080 --join=localhost:26257,localhost:26258,localhost:26259 503 53651 1 0 10:18AM ttys013 0:38.81 cockroach start --insecure --store=fault-node2 --listen-addr=localhost:26258 --http-addr=localhost:8081 --join=localhost:26257,localhost:26258,localhost:26259 503 53671 1 0 10:18AM ttys013 0:35.40 cockroach start --insecure --store=fault-node3 --listen-addr=localhost:26259 --http-addr=localhost:8082 --join=localhost:26257,localhost:26258,localhost:26259 503 53684 1 0 10:18AM ttys013 0:38.44 cockroach start --insecure --store=fault-node4 --listen-addr=localhost:26260 --http-addr=localhost:8083 --join=localhost:26257,localhost:26258,localhost:26259 503 53708 1 0 10:18AM ttys013 0:39.49 cockroach start --insecure --store=fault-node5 --listen-addr=localhost:26261 --http-addr=localhost:8084 --join=localhost:26257,localhost:26258,localhost:26259 503 53730 1 0 10:18AM ttys013 0:33.37 cockroach start --insecure --store=fault-node6 --listen-addr=localhost:26262 --http-addr=localhost:8085 --join=localhost:26257,localhost:26258,localhost:26259 ``` 3. Gracefully shut down the node stored in `fault-node5`, specifying its process ID (in this example, `53708`): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kill -TERM 53708 ``` ### Step 6. Check load continuity and cluster health Go back to the DB Console, click **Metrics** on the left, and verify that the cluster as a whole continues serving data, despite one of the nodes being unavailable and marked as **Suspect**: ![DB Console Suspect Node](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-7.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=8151cbad1a96492bb7ae6435859ecfe8) This shows that when all ranges are replicated 3 times (the default), the cluster can tolerate a single node failure because the surviving nodes have a majority of each range's replicas (2/3). ### Step 7. Watch the cluster repair itself Click **Overview** on the left: ![DB Console Cluster Repair](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-5.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=19b682470b7a9dbe22f0441df579d162) Because you reduced the time it takes for the cluster to consider the down node dead, after 1 minute or so, the cluster will consider the down node "dead", and you'll see the replica count on the remaining nodes increase and the number of under-replicated ranges decrease to 0. This shows the cluster repairing itself by re-replicating missing replicas. ### Step 8. Prepare for two simultaneous node failures At this point, the cluster has recovered and is ready to handle another failure. However, the cluster cannot handle two *near-simultaneous* failures in this configuration. Failures are "near-simultaneous" if they are closer together than the `server.time_until_store_dead` [cluster setting](/docs/v26.4/cluster-settings) plus the time taken for the number of replicas on the dead node to drop to zero. If two failures occurred in this configuration, some ranges would become unavailable until one of the nodes recovers. To be able to tolerate 2 of 5 nodes failing simultaneously without any service interruption, ranges must be replicated 5 times. 1. In the terminal window where you started `fault-node5` initially, start it again using the same command you used to [start the node initially](#step-1-start-a-6-node-cluster): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --insecure \ --store=fault-node5 \ --listen-addr=localhost:26261 \ --http-addr=localhost:8084 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` 2. Use the [`ALTER RANGE ... CONFIGURE ZONE`](/docs/v26.4/alter-range#configure-zone) command to change the cluster's `default` replication factor to 5: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost:26000 \ --execute="ALTER RANGE default CONFIGURE ZONE USING num_replicas=5;" ``` 3. In the DB Console **Overview** dashboard, watch the replica count increase and even out across all 6 nodes: ![DB Console Cluster Restore](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-8.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=df3198838cdd31a56fb5045ae10a465d) This shows the cluster up-replicating so that each range has 5 replicas, one on each node. ### Step 9. Simulate two simultaneous node failures Gracefully shut down **2 nodes**, specifying the [process IDs you retrieved earlier](#step-5-simulate-a-single-node-failure): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kill -TERM {process IDs} ``` ### Step 10. Check cluster status and service continuity 1. Click **Overview** on the left, and verify the state of the cluster: ![DB Console Cluster Health](https://mintcdn.com/cockroachlabs/bBD0UEapbn6fk8Rb/images/common/fault-tolerance-9.png?fit=max\&auto=format\&n=bBD0UEapbn6fk8Rb\&q=85\&s=19f459b9ef70b32173eb5ffee502cdf9) 2. To verify that the cluster still serves data, use the `cockroach sql` command to interact with the cluster. Count the number of rows in the `ycsb.public.usertable` table to see that it serves reads: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost:26257 \ --execute="SELECT count(*) FROM ycsb.public.usertable;" ``` ``` count +-------+ 10000 (1 row) ``` Insert data to see that it serves writes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost:26257 \ --execute="INSERT INTO ycsb.public.usertable VALUES ('asdf', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);" ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost:26257 \ --execute="SELECT count(*) FROM ycsb.public.usertable;" ``` ``` count +-------+ 10001 (1 row) ``` This shows that when all ranges are replicated 5 times, the cluster can tolerate 2 simultaneous node outages because the surviving nodes have a majority of each range's replicas (3/5). ### Step 11. Clean up 1. In the terminal where the YCSB workload is running, press **CTRL + c**. 2. Terminate HAProxy: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pkill haproxy ``` 3. Gracefully shut down the remaining **4 nodes**, specifying the [process IDs you retrieved earlier](#step-5-simulate-a-single-node-failure) and the new process ID for the node stored in `fault-node5`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kill -TERM {process IDs} ``` > [!NOTE] > > For the final 2 nodes, the shutdown process will take longer (about a minute each) and will eventually force the nodes to stop. This is because, with only 2 of 5 nodes left, a majority of replicas are not available, and so the cluster is no longer operational. 1. To restart the cluster at a later time, run the same `cockroach start` commands as in [Step 1. Start a 6-node cluster](#step-1-start-a-6-node-cluster) from the directory containing the nodes' data stores. 2. If you do not plan to restart the cluster, you may want to remove the nodes' data stores and the HAProxy config files: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ rm -rf fault-node1 fault-node2 fault-node3 fault-node4 fault-node5 fault-node6 haproxy.cfg haproxy.cfg.saved ``` ## What's next? Explore other CockroachDB benefits and features: * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Serializable Transactions](/docs/v26.4/demo-serializable) # Replication and Rebalancing Source: https://docs.cockroachlabs.com/docs/stable/demo-replication-and-rebalancing This page guides you through a simple demonstration of how CockroachDB replicates, distributes, and rebalances data. Starting with a 3-node local cluster, you'll write some data and verify that it replicates in triplicate by default. You'll then add 2 more nodes and watch how CockroachDB automatically rebalances replicas to efficiently use all available capacity. ## Before you begin Make sure you have already [installed CockroachDB](/docs/v26.4/install-cockroachdb-mac). ## Step 1. Generate certificates 1. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs my-safe-directory ``` 2. Create the CA (Certificate Authority) certificate and key pair: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 3. Create the certificate and key pair for your nodes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ localhost \ $(hostname) \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` Because you're running a local cluster and all nodes use the same hostname (`localhost`), you only need a single node certificate. Note that this is different than running a production cluster, where you would need to generate a certificate and key for each node, issued to all common names and IP addresses you might use to refer to the node as well as to any load balancer instances. 4. Create a client certificate and key pair for the `root` user: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-client \ root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` ## Step 2. Start a 3-node cluster 1. Use the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command to start node 1: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --certs-dir=certs \ --store=rep-node1 \ --listen-addr=localhost:26257 \ --http-addr=localhost:8080 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` 2. In a new terminal, start node 2: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --certs-dir=certs \ --store=rep-node2 \ --listen-addr=localhost:26258 \ --http-addr=localhost:8081 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` 3. In a new terminal, start node 3: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --certs-dir=certs \ --store=rep-node3 \ --listen-addr=localhost:26259 \ --http-addr=localhost:8082 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` 4. In a new terminal, use the [`cockroach init`](/docs/v26.4/cockroach-init) command to perform a one-time initialization of the cluster, sending the request to any node on the `--join` list: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --certs-dir=certs --host=localhost:26257 ``` You'll see the following message: ``` Cluster successfully initialized ``` At this point, each node also prints helpful [startup details](/docs/v26.4/cockroach-start#standard-output) to its log. ## Step 3. Create a SQL user You'll use a non-`root` user for running a client workload and accessing the DB Console. 1. In the same terminal, as the `root` user, open the [built-in SQL shell](/docs/v26.4/cockroach-sql) against any node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql \ --certs-dir=certs \ --host=localhost:26257 ``` 2. Create the `maxroach` user with a password: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE USER maxroach WITH PASSWORD ' GRANT admin TO maxroach; ``` This role assignment is for convenience for this tutorial; it gives the user access to all data without the need for additional privileges. For more details, see [Authorization](/docs/v26.4/security-reference/authorization#admin-role). 4. Exit the SQL shell: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ## Step 4. Write data 1. In the same terminal, run the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to generate an example `intro` database. In the connection string, replace ` SHOW DATABASES; ``` ``` database_name +---------------+ defaultdb intro postgres system (4 rows) ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW TABLES FROM intro; ``` ``` table_name -------------- mytable (1 row) ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM intro.mytable WHERE (l % 2) = 0; ``` ``` l | v +----+------------------------------------------------------+ 0 | !__aaawwmqmqmwwwaas,,_ .__aaawwwmqmqmwwaaa,, 2 | !"VT?!"""^~~^"""??T$Wmqaa,_auqmWBT?!"""^~~^^""??YV^ 4 | ! "?##mW##?"- 6 | ! C O N G R A T S _am#Z??A#ma, Y 8 | ! _ummY" "9#ma, A 10 | ! vm#Z( )Xmms Y 12 | ! .j####mmm#####mm#m##6. 14 | ! W O W ! jmm###mm######m#mmm##6 16 | ! ]#me*Xm#m#mm##m#m##SX##c 18 | ! dm#||+*$##m#mm#m#Svvn##m 20 | ! :mmE=|+||S##m##m#1nvnnX##; A 22 | ! :m#h+|+++=Xmm#m#1nvnnvdmm; M 24 | ! Y $#m>+|+|||##m#1nvnnnnmm# A 26 | ! O ]##z+|+|+|3#mEnnnnvnd##f Z 28 | ! U D 4##c|+|+|]m#kvnvnno##P E 30 | ! I 4#ma+|++]mmhvnnvq##P` ! 32 | ! D I ?$#q%+|dmmmvnnm##! 34 | ! T -4##wu#mm#pw##7' 36 | ! -?$##m####Y' 38 | ! !! "Y##Y"- 40 | ! (21 rows) ``` 4. Exit the SQL shell: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ## Step 5. Verify replication 1. To understand replication in CockroachDB, it's important to review a few concepts from the [architecture](/docs/v26.4/architecture/overview): | Concept | Description | | - | - | | **Range** | CockroachDB stores all user data (tables, indexes, etc.) and almost all system data in a giant sorted map of key-value pairs. This keyspace is divided into "ranges", contiguous chunks of the keyspace, so that every key can always be found in a single range. From a SQL perspective, a table and its secondary indexes initially map to a single range, where each key-value pair in the range represents a single row in the table (also called the primary index because the table is sorted by the primary key) or a single row in a secondary index. As soon as that range reaches [the maximum range size](/docs/v26.4/configure-replication-zones#range-max-bytes), it [splits into two ranges](/docs/v26.4/architecture/distribution-layer#range-splits). This process continues for these new ranges as the table and its indexes continue growing. | | **Replica** | CockroachDB replicates each range (3 times by default) and stores each replica on a different node. | 2. With those concepts in mind, open the DB Console at [http://localhost:8080](http://localhost:8080) and log in with the `maxroach` user. 3. On the **Overview** page, note that the **Replicas** count is the same on all three nodes. This indicates: * There are this many "ranges" of data in the cluster. These are mostly internal "system" ranges since you haven't added much table data. * Each range has been replicated 3 times (according to the CockroachDB default). * For each range, each replica is stored on different nodes. ## Step 6. Add two more nodes 1. Back in the terminal, add a fourth node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --certs-dir=certs \ --store=rep-node4 \ --listen-addr=localhost:26260 \ --http-addr=localhost:8083 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` 2. In a new terminal, add a fifth node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --certs-dir=certs \ --store=rep-node5 \ --listen-addr=localhost:26261 \ --http-addr=localhost:8084 \ --join=localhost:26257,localhost:26258,localhost:26259 ``` ## Step 7. Watch data rebalance Back in the DB Console, you'll see that there are now 5 nodes listed. At first, the replica count will be lower for nodes 4 and 5. Very soon, however, you'll see those numbers even out across all nodes, indicating that data is being automatically rebalanced to utilize the additional capacity of the new nodes. ## Step 8. Stop the cluster 1. When you're done with your test cluster, press `ctrl-c` in each terminal where a node is running. > [!NOTE] > > For the last 2 nodes, the shutdown process will take longer (about a minute each) and will eventually force the nodes to stop. This is because, with only 2 of 5 nodes left, a majority of replicas are not available, and so the cluster is no longer operational. To speed up this process, you can press `ctrl-c` a second time. 1. To restart the cluster at a later time, run the same `cockroach start` commands as earlier from the directory containing the nodes' data stores. If you do not plan to restart the cluster, you may want to remove the cluster's certificates and data stores: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ rm -rf certs my-safe-directory rep-node1 rep-node2 rep-node3 rep-node4 rep-node5 ``` ## What's next? Explore other CockroachDB benefits and features: * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Serializable Transactions](/docs/v26.4/demo-serializable) # Serializable Transactions Source: https://docs.cockroachlabs.com/docs/stable/demo-serializable In contrast to most databases, CockroachDB offers `SERIALIZABLE` isolation by default, which is the strongest of the four [transaction isolation levels](https://wikipedia.org/wiki/Isolation_\(database_systems\)) defined by the SQL standard and is stronger than the `SNAPSHOT` isolation level developed later. `SERIALIZABLE` isolation guarantees that even though transactions may execute in parallel, the result is the same as if they had executed one at a time, without any concurrency. This ensures data correctness by preventing all "anomalies" allowed by weaker isolation levels. In this tutorial, you'll work through a hypothetical scenario that demonstrates the effectiveness of `SERIALIZABLE` isolation for maintaining data correctness. 1. You'll start by reviewing the scenario and its schema. 2. You'll finish by executing the scenario at `SERIALIZABLE` isolation, observing how it guarantees correctness. You'll use CockroachDB for this portion. > [!NOTE] > > For a deeper discussion of transaction isolation and the write skew anomaly, see the [Real Transactions are Serializable](https://www.cockroachlabs.com/blog/acid-rain/) and [What Write Skew Looks Like](https://www.cockroachlabs.com/blog/what-write-skew-looks-like/) blog posts. ## Overview ### Scenario * A hospital has an application for doctors to manage their on-call shifts. * The hospital has a rule that at least one doctor must be on call at any one time. * Two doctors are on-call for a particular shift, and both of them try to request leave for the shift at approximately the same time. * In PostgreSQL, with the default [`READ COMMITTED`](/docs/v26.4/read-committed) isolation level, the [write skew](#write-skew) anomaly results in both doctors successfully booking leave and the hospital having no doctors on call for that particular shift. * In CockroachDB, with the `SERIALIZABLE` isolation level, write skew is prevented, one doctor is allowed to book leave and the other is left on-call, and lives are saved. #### Write skew When write skew happens, a transaction reads something, makes a decision based on the value it saw, and writes the decision to the database. However, by the time the write is made, the premise of the decision is no longer true. Only `SERIALIZABLE` and some implementations of `REPEATABLE READ` isolation prevent this anomaly. ### Schema ![Schema for serializable transaction tutorial](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/serializable_schema.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=11602a505045d731e96a8522ed02826d) ## Step 1. Set up the scenario on PostgreSQL 1. If you haven't already, install PostgreSQL locally. On Mac, you can use [Homebrew](https://brew.sh/): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ brew install postgres ``` 2. [Start PostgreSQL](https://www.postgresql.org/docs/10/static/server-start.html): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ postgres -D /usr/local/var/postgres & ``` 3. Open a SQL connection to PostgreSQL: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ psql ``` 4. Create the `doctors` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE doctors ( id INT PRIMARY KEY, name TEXT ); ``` 5. Create the `schedules` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE schedules ( day DATE, doctor_id INT REFERENCES doctors (id), on_call BOOL, PRIMARY KEY (day, doctor_id) ); ``` 6. Add two doctors to the `doctors` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO doctors VALUES (1, 'Abe'), (2, 'Betty'); ``` 7. Insert one week's worth of data into the `schedules` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO schedules VALUES ('2024-10-01', 1, true), ('2024-10-01', 2, true), ('2024-10-02', 1, true), ('2024-10-02', 2, true), ('2024-10-03', 1, true), ('2024-10-03', 2, true), ('2024-10-04', 1, true), ('2024-10-04', 2, true), ('2024-10-05', 1, true), ('2024-10-05', 2, true), ('2024-10-06', 1, true), ('2024-10-06', 2, true), ('2024-10-07', 1, true), ('2024-10-07', 2, true); ``` 8. Confirm that at least one doctor is on call each day of the week: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT day, count(*) AS doctors_on_call FROM schedules WHERE on_call = true GROUP BY day ORDER BY day; ``` ``` day | doctors_on_call ------------+----------------- 2024-10-01 | 2 2024-10-02 | 2 2024-10-03 | 2 2024-10-04 | 2 2024-10-05 | 2 2024-10-06 | 2 2024-10-07 | 2 (7 rows) ``` ## Step 2. Run the scenario on PostgreSQL 1. Doctor 1, Abe, starts to request leave for 10/5/18 using the hospital's schedule management application. The application starts a transaction: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > BEGIN; ``` 2. The application checks to make sure at least one other doctor is on call for the requested date: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT count(*) FROM schedules WHERE on_call = true AND day = '2024-10-05' AND doctor_id != 1; ``` ``` count ------- 1 (1 row) ``` 3. Around the same time, doctor 2, Betty, starts to request leave for the same day using the hospital's schedule management application. In a new terminal, start a second SQL session: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ psql ``` 4. The application starts a transaction: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > BEGIN; ``` 5. The application checks to make sure at least one other doctor is on call for the requested date: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT count(*) FROM schedules WHERE on_call = true AND day = '2024-10-05' AND doctor_id != 2; ``` ``` count ------- 1 (1 row) ``` 6. In the terminal for doctor 1, since the previous check confirmed that another doctor is on call for 10/5/18, the application tries to update doctor 1's schedule: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE schedules SET on_call = false WHERE day = '2024-10-05' AND doctor_id = 1; ``` 7. In the terminal for doctor 2, since the previous check confirmed the same thing, the application tries to update doctor 2's schedule: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE schedules SET on_call = false WHERE day = '2024-10-05' AND doctor_id = 2; ``` 8. In the terminal for doctor 1, the application commits the transaction, despite the fact that the previous check (the `SELECT` query) is no longer true: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > COMMIT; ``` 9. In the terminal for doctor 2, the application commits the transaction, despite the fact that the previous check (the `SELECT` query) is no longer true: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > COMMIT; ``` ## Step 3. Check data correctness on PostgreSQL So what just happened? Each transaction started by reading a value that, before the end of the transaction, became incorrect. Despite that fact, each transaction was allowed to commit. This is known as write skew, and the result is that 0 doctors are scheduled to be on call on 10/5/18. To check this, in either terminal, run: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM schedules WHERE day = '2024-10-05'; ``` ``` day | doctor_id | on_call ------------+-----------+--------- 2024-10-05 | 1 | f 2024-10-05 | 2 | f (2 rows) ``` Again, this anomaly is the result of PostgreSQL's default isolation level of [`READ COMMITTED`](/docs/v26.4/read-committed), but note that this would happen with any isolation level except `SERIALIZABLE` and some implementations of `REPEATABLE READ`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW TRANSACTION_ISOLATION; ``` ``` transaction_isolation ----------------------- read committed (1 row) ``` Exit each SQL shell with `\q` and then stop the PostgreSQL server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ pkill -9 postgres ``` ## Step 4. Set up the scenario on CockroachDB When you repeat the scenario on CockroachDB, you'll see that the anomaly is prevented by CockroachDB's `SERIALIZABLE` transaction isolation. 1. If you haven't already, [install CockroachDB](/docs/v26.4/install-cockroachdb-mac) locally. 2. Use the [`cockroach start-single-node`](/docs/v26.4/cockroach-start-single-node) command to start a one-node CockroachDB cluster in insecure mode: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start-single-node \ --insecure \ --store=serializable-demo \ --listen-addr=localhost ``` 3. In a new terminal window, open the [built-in SQL client](/docs/v26.4/cockroach-sql) and connect to `localhost`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost ``` 4. Create the `doctors` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE doctors ( id INT PRIMARY KEY, name TEXT ); ``` 5. Create the `schedules` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE schedules ( day DATE, doctor_id INT REFERENCES doctors (id), on_call BOOL, PRIMARY KEY (day, doctor_id) ); ``` 6. Add two doctors to the `doctors` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO doctors VALUES (1, 'Abe'), (2, 'Betty'); ``` 7. Insert one week's worth of data into the `schedules` table: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO schedules VALUES ('2024-10-01', 1, true), ('2024-10-01', 2, true), ('2024-10-02', 1, true), ('2024-10-02', 2, true), ('2024-10-03', 1, true), ('2024-10-03', 2, true), ('2024-10-04', 1, true), ('2024-10-04', 2, true), ('2024-10-05', 1, true), ('2024-10-05', 2, true), ('2024-10-06', 1, true), ('2024-10-06', 2, true), ('2024-10-07', 1, true), ('2024-10-07', 2, true); ``` 8. Confirm that at least one doctor is on call each day of the week: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT day, count(*) AS on_call FROM schedules WHERE on_call = true GROUP BY day ORDER BY day; ``` ``` day | on_call -------------+---------- 2024-10-01 | 2 2024-10-02 | 2 2024-10-03 | 2 2024-10-04 | 2 2024-10-05 | 2 2024-10-06 | 2 2024-10-07 | 2 (7 rows) ``` ## Step 5. Run the scenario on CockroachDB 1. Doctor 1, Abe, starts to request leave for 10/5/18 using the hospital's schedule management application. The application starts a transaction: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > BEGIN; ``` 2. The application checks to make sure at least one other doctor is on call for the requested date: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT count(*) FROM schedules WHERE on_call = true AND day = '2024-10-05' AND doctor_id != 1; ``` ``` count --------- 1 (1 row) ``` 3. Around the same time, doctor 2, Betty, starts to request leave for the same day using the hospital's schedule management application. In a new terminal, start a second SQL session: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=localhost ``` 4. The application starts a transaction: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > BEGIN; ``` 5. The application checks to make sure at least one other doctor is on call for the requested date: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT count(*) FROM schedules WHERE on_call = true AND day = '2024-10-05' AND doctor_id != 2; ``` ``` count --------- 1 (1 row) ``` 6. In the terminal for doctor 1, since the previous check confirmed that another doctor is on call for 10/5/18, the application tries to update doctor 1's schedule: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE schedules SET on_call = false WHERE day = '2024-10-05' AND doctor_id = 1; ``` 7. In the terminal for doctor 2, since the previous check confirmed the same thing, the application tries to update doctor 2's schedule: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE schedules SET on_call = false WHERE day = '2024-10-05' AND doctor_id = 2; ``` 8. In the terminal for doctor 1, the application tries to commit the transaction: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > COMMIT; ``` The transaction for doctor 1 is committed. 9. In the terminal for doctor 2, the application tries to commit the transaction: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > COMMIT; ``` Since CockroachDB uses `SERIALIZABLE` isolation, the database detects that the previous check (the `SELECT` query) is no longer true due to a concurrent transaction. It therefore prevents the transaction from committing, returning a retry error that indicates that the transaction must be attempted again. ``` ERROR: restart transaction: TransactionRetryWithProtoRefreshError: TransactionRetryError: retry txn (RETRY_SERIALIZABLE - failed preemptive refresh due to encountered recently written committed value /Table/105/1/20001/1/0 @1700513356.063385000,2): "sql txn" meta={id=10f4abbc key=/Table/105/1/20001/2/0 iso=Serializable pri=0.00167708 epo=0 ts=1700513366.194063000,2 min=1700513327.262632000,0 seq=1} lock=true stat=PENDING rts=1700513327.262632000,0 wto=false gul=1700513327.762632000,0 SQLSTATE: 40001 HINT: See: https://www.cockroachlabs.com/docs/v26.4/transaction-retry-error-reference.html#retry_serializable ``` > [!TIP] > > For this kind of error, CockroachDB recommends a [client-side transaction retry loop](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling) that would transparently observe that the one doctor cannot take time off because the other doctor already succeeded in asking for it. You can find generic transaction retry functions for various languages in the [Develop with CockroachDB](/docs/v26.4/developer-basics) section. > > For more information about the error message for the `RETRY_SERIALIZABLE` error type, see the [Transaction Retry Error Reference](/docs/v26.4/transaction-retry-error-reference#retry_serializable). ## Step 6. Check data correctness on CockroachDB 1. In either terminal, confirm that one doctor is still on call for 10/5/18: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM schedules WHERE day = '2024-10-05'; ``` ``` day | doctor_id | on_call -------------+-----------+---------- 2024-10-05 | 1 | f 2024-10-05 | 2 | t (2 rows) ``` 2. Again, the write skew anomaly was prevented by CockroachDB using the `SERIALIZABLE` isolation level: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW TRANSACTION_ISOLATION; ``` ``` transaction_isolation ------------------------- serializable (1 row) ``` 3. Exit the SQL shell in each terminal: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` 4. Exit each SQL shell with `\q` and then stop the node: Get the process ID of the node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ps -ef | grep cockroach | grep -v grep ``` ``` 501 21691 1 0 6:19PM ttys001 0:01.15 cockroach start-single-node --insecure --store=serializable-demo --listen-addr=localhost ``` Gracefully shut down the node, specifying its process ID: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kill -TERM 21691 ``` ``` initiating graceful shutdown of server server drained and shutdown completed ``` If you do not plan to restart the cluster, you may want to remove the node's data store: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ rm -rf serializable-demo ``` ## What's next? Explore other CockroachDB benefits and features: * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Serializable Transactions](/docs/v26.4/demo-serializable) You might also want to learn more about how transactions work in CockroachDB and in general: * [Transactions Overview](/docs/v26.4/transactions) * [What Write Skew Looks Like](https://www.cockroachlabs.com/blog/what-write-skew-looks-like/) * [Read Committed Transactions](/docs/v26.4/read-committed) # Deploy a CockroachDB Cloud Application with Google Cloud Run Source: https://docs.cockroachlabs.com/docs/stable/deploy-app-gcr This tutorial shows you how to use Google Cloud Run to deploy a containerized Django application that communicates with a CockroachDB Standard cluster. ## Before you begin Before starting the tutorial, do the following: 1. Create a [Google Cloud](https://cloud.google.com/) account and log in. 2. Install the [Google Cloud SDK](https://cloud.google.com/sdk). 3. Install [Docker Desktop](https://www.docker.com/products/docker-desktop). ## Step 1. Create a CockroachDB Standard cluster 1. [Create a CockroachDB Cloud account](/docs/cockroachcloud/create-an-account). If this is your first CockroachDB Cloud organization, it will be credited with \$400 in [free trial credits](/docs/cockroachcloud/free-trial) to get you started. 2. On the **Get Started** page, click **Create cluster**. 3. On the **Select a plan** page, select **Standard**. 4. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS). 5. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Standard clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. 6. Click **Next: Capacity**. 7. On the **Capacity** page, keep the [**Provisioned capacity**](/docs/cockroachcloud/plan-your-cluster) at the default value of 2 vCPUs. Click **Next: Finalize**. 8. On the **Finalize** page, name your cluster. If an active free trial is listed in the right pane, you will not need to add a payment method, though you will need to do this by the [end of the trial](/docs/cockroachcloud/free-trial#add-payment-methods) to maintain your organization's clusters. Click **Create cluster**. Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. ## Step 2. Set up your cluster connection Once your cluster is created, the **Connect to cluster-name** dialog displays. Use the information provided in the dialog to set up your cluster connection for the SQL user that was created by default: 1. In your terminal, run the second command from the dialog to create a new `certs` directory on your local machine and download the CA certificate to that directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --create-dirs -o ~/.postgresql/root.crt -O https://cockroachlabs.cloud/clusters/{cluster-id}/cert ``` Your `cert` file will be downloaded to `~/.postgresql/root.crt`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --create-dirs -o ~/.postgresql/root.crt -O https://cockroachlabs.cloud/clusters/{cluster-id}/cert ``` Your `cert` file will be downloaded to `~/.postgresql/root.crt`. ```powershell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} mkdir -p $env:appdata\.postgresql\; Invoke-WebRequest -Uri https://cockroachlabs.cloud/clusters/{cluster-id}/cert -OutFile $env:appdata\.postgresql\root.crt ``` Your `cert` file will be downloaded to `%APPDATA%/.postgresql/root.crt`. 2. Copy the connection string provided, which will be used in the next steps (and to connect to your cluster in the future). > [!CAUTION] > > This connection string contains your password, which will be provided only once. If you forget your password, you can reset it by going to the **SQL Users** page for the cluster, found at `https://cockroachlabs.cloud/cluster//users`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --url 'postgresql:// CREATE DATABASE bank; ``` 4. Exit the SQL shell: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ## Step 4. Get the application code 1. Clone the example code's GitHub repo: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} git clone https://github.com/cockroachlabs/example-app-python-django/ ``` 2. Create a new directory named `certs` at the top level of the `example-app-python-django` project, and then copy the root certificate that you downloaded for your cluster to the new directory. The project directory structure should look like this: ``` ├── Dockerfile ├── README.md ├── certs │   └── root.crt ├── cockroach_example │   ├── cockroach_example │   │   ├── __init__.py │   │   ├── asgi.py │   │   ├── migrations │   │   │   ├── 0001_initial.py │   │   │   └── __init__.py │   │   ├── models.py │   │   ├── settings.py │   │   ├── urls.py │   │   ├── views.py │   │   └── wsgi.py │   └── manage.py └── requirements.txt ``` ## Step 5. Initialize the database and test the app locally 1. At the top level of the app's project directory, create and then activate a virtual environment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} virtualenv env ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} source env/bin/activate ``` 2. Install the required modules to the virtual environment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} pip install -r requirements.txt ``` 3. Set the `DATABASE_URL` environment variable to the connection string provided in the **Connection info** window of the CockroachDB Cloud Console, but with the root certificate located in the local `certs` directory: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export DATABASE_URL="postgresql://$USER:$PASSWORD@random-cluster-name-4300.6wr.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=root.crt" ``` This Django app uses the `dj_database_url` module to configure the database connection from a connection URL. The module uses the value assigned to the `DATABASE_URL` environment variable for the connection. > [!NOTE] > > In the Cloud Run deployment, we use the Google Cloud Secret Manager to define the `DATABASE_URL` environment variable for the deployment. 1. Execute the initial database schema migration: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} python3 cockroach_example/manage.py migrate ``` This migration initializes the `bank` database with the tables defined in `models.py`, in addition to some other tables for the admin functionality included with Django's starter application. 2. Run the app: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} python3 cockroach_example/manage.py runserver 0.0.0.0:8000 ``` The output should look like this: ``` ... Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. ``` To perform simple reads and writes to the database, you can send HTTP requests to the application at [http://0.0.0.0:8000/](http://0.0.0.0:8000/). 3. In a new terminal, use `curl` to send a POST request to the application: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl --header "Content-Type: application/json" \ --request POST \ --data '{"name":"Carl"}' http://0.0.0.0:8000/customer/ ``` This request inserts a new row into the `cockroach_example_customers` table. 4. Send a GET request to read from the `cockroach_example_customers` table: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl http://0.0.0.0:8000/customer/ ``` ``` [{"id": "bb7d6c4d-efb3-45f8-b790-9911aae7d8b2", "name": "Carl"}] ``` You can also query the table directly in the [SQL shell](/docs/v26.4/cockroach-sql) to see the changes: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.cockroach_example_customers; ``` ``` id | name ---------------------------------------+------- bb7d6c4d-efb3-45f8-b790-9911aae7d8b2 | Carl (1 row) ``` 5. Enter **Ctrl+C** to stop the application. ## Step 6. Configure GCP 1. In the terminal, authenticate the `gcloud` command-line tool with your Google Cloud account: > [!NOTE] > > `gcloud` is included with the [Google Cloud SDK](https://cloud.google.com/sdk) installation. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud auth login ``` Follow the prompts to authenticate. 1. Create a Google Cloud project for the application deployment: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud projects create {gcp_project_id} ``` > [!NOTE] > > You can specify a location for the project within your Google Cloud resources by using the `--organization` or `--folder` flags. 1. Configure the CLI to use your Google Cloud account and the new project ID by default: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud init ``` 2. Set the `PROJECT_ID` environment variable: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export PROJECT_ID={gcp_project_id} ``` For the rest of the tutorial, we use `PROJECT_ID` to refer to the project ID. ## Step 7. Containerize the application and push it to the registry 1. Build the Docker image locally: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} docker build -t gcr.io/$PROJECT_ID/crdb-sample:v1 . ``` If there are no errors, the container built successfully. 2. Authenticate Docker with GCP's Container Registry: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud auth configure-docker ``` 3. Enable the Container Registry API for the project: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud services enable containerregistry.googleapis.com ``` 4. Push the Docker image to the project's registry. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} docker push gcr.io/$PROJECT_ID/crdb-sample:v1 ``` ## Step 8. Create a secret for the database connection URI 1. Create a service account to manage the secrets for your project: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud iam service-accounts create cockroach-labs ``` 2. Enable the Secret Manager API for the project: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud services enable secretmanager.googleapis.com ``` 3. Create a secret for the connection string stored locally in the `DATABASE_URL` environment variable, and bind the new service account to the secret. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} echo $DATABASE_URL | gcloud secrets create cockroach-connection-uri --data-file=- --replication-policy=automatic ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud secrets add-iam-policy-binding cockroach-connection-uri \ --member=serviceAccount:cockroach-labs@${PROJECT_ID}.iam.gserviceaccount.com \ --role=roles/secretmanager.secretAccessor ``` ## Step 9. Deploy the application on Cloud Run 1. Enable the Cloud Run API for the project: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud services enable run.googleapis.com ``` 2. Create a [Cloud Run](https://console.cloud.google.com/run/) service for the application: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud alpha run deploy crl-app \ --region us-central1 \ --allow-unauthenticated \ --service-account "cockroach-labs@${PROJECT_ID}.iam.gserviceaccount.com" \ --set-secrets "DATABASE_URL=cockroach-connection-uri:latest" \ --image gcr.io/${PROJECT_ID}/crdb-sample:v1 ``` Note the following: * The `--region` flag specifies the region of the CockroachDB node targeted in the connection string. * The `--service-account` flag specifies the `cockroach-labs` service account that you created earlier for the app deployment. * The `--set-secrets` flag sets the `DATABASE_URL` environment variable to the `cockroach-connection-uri` secret that you created earlier. * The `--image` flag specifies the container image URL for the `crdb-sample` image that you pushed to the container registry. If prompted, select `Cloud Run (fully managed)`. 3. After the revision is deployed, verify that you can send requests to the application from a browser or a REST client: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl https:///customer/ ``` ``` [{"id": "bb7d6c4d-efb3-45f8-b790-9911aae7d8b2", "name": "Carl"}] ``` 4. By default, the sample application allows all hosts/domain names to serve the application. After testing, we recommend that you update the [`ALLOWED_HOSTS` property in `settings.py`](https://docs.djangoproject.com/en/3.2/ref/settings/#allowed-hosts) to allow only a local testing URL and the Cloud Run service URL to serve the application. ## See also * [Build a Simple Django App with CockroachDB](/docs/v26.4/build-a-python-app-with-cockroachdb-django) You might also be interested in the following pages: * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Connection Pooling](/docs/v26.4/connection-pooling) * [Data Replication](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) # Deploy a Netlify App Built on CockroachDB Source: https://docs.cockroachlabs.com/docs/stable/deploy-app-netlify This tutorial shows you how to deploy a [Netlify](https://www.netlify.com/) web application that communicates with a CockroachDB Standard cluster. The sample app used in this tutorial simulates a [gaming leaderboard](https://www.cockroachlabs.com/blog/react-typescript-cockroachdb-sample-app/) using [Netlify functions](https://www.netlify.com/products/functions/) written in TypeScript. The functions use [Prisma](https://www.prisma.io/) to connect to CockroachDB. The app's frontend, also written in TypeScript, uses React, bootstrapped with [Create React App](https://github.com/facebook/create-react-app). You can view or download the [source code](https://github.com/cockroachdb/cockroachdb-typescript) for the example. ## Before you begin Before starting the tutorial: 1. Create a Starter [Netlify](https://app.netlify.com/signup) account. 2. Install the `netlify` CLI locally and log in. Refer to [Get started with Netlify CLI](https://docs.netlify.com/cli/get-started/). ## Step 1. Create a CockroachDB Standard cluster 1. [Create a CockroachDB Cloud account](/docs/cockroachcloud/create-an-account). If this is your first CockroachDB Cloud organization, it will be credited with \$400 in [free trial credits](/docs/cockroachcloud/free-trial) to get you started. 2. On the **Get Started** page, click **Create cluster**. 3. On the **Select a plan** page, select **Standard**. 4. On the **Cloud & Regions** page, select a cloud provider (GCP or AWS). 5. In the **Regions** section, select a region for the cluster. Refer to [CockroachDB Cloud Regions](/docs/cockroachcloud/regions) for the regions where CockroachDB Standard clusters can be deployed. To create a multi-region cluster, click **Add region** and select additional regions. 6. Click **Next: Capacity**. 7. On the **Capacity** page, keep the [**Provisioned capacity**](/docs/cockroachcloud/plan-your-cluster) at the default value of 2 vCPUs. Click **Next: Finalize**. 8. On the **Finalize** page, name your cluster. If an active free trial is listed in the right pane, you will not need to add a payment method, though you will need to do this by the [end of the trial](/docs/cockroachcloud/free-trial#add-payment-methods) to maintain your organization's clusters. Click **Create cluster**. Your cluster will be created in a few seconds and the **Create SQL user** dialog will display. After the cluster is created, the **Connection info** window appears. Click the **Connection string** tab and copy the connection string to a secure location. You will use this connection string to connect to CockroachDB later in the tutorial. The connection string is pre-populated with your SQL username and password, the cluster name, and other details. Save the password in a secure place such a password manager. You can find the connection string at any time from the CockroachDB Cloud Console. You can reset your SQL password for this cluster from the cluster's **SQL Users** page. ## Step 2. Get the code 1. Open the code repository's [GitHub repository](https://github.com/cockroachdb/cockroachdb-typescript). 2. Fork it by clicking **Fork** at the top. Netlify requires you to own a Netlify app's repository. * Set **Owner** to your GitHub identity or an organization. * Disable **Copy the master branch only**. * Click **Fork**. You now have an exact copy of the code repository in the GitHub location you chose. 3. Copy the fork's address, which you will use to clone it locally. Click **Code**, then in the **Local** tab, click **SSH** if you have added SSH keys to GitHub, or **HTTPS** if not. Click the copy symbol to copy the address. 4. Clone your fork locally. Replace `{ADDRESS}` with the full address of your fork, which will end with `cockroachdb-typescript.git`. The project has the following directory structure: ``` ├── LICENSE.md ├── README.md ├── netlify │   └── functions │   ├── addScore.ts │   ├── getPlayers.ts │   └── getScores.ts ├── package-lock.json ├── package.json ├── prisma │   ├── schema.prisma │   └── seed.ts ├── public ├── src └── tsconfig.json ``` This tutorial modifies the files in the `netlify` and `prisma` directories. ## Step 3. Initialize the database 1. Open the project's `.env` file in a text editor set the `DATABASE_URL` environment variable to [the connection string](#connection-string) you obtained earlier from the CockroachDB Cloud Console: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} DATABASE_URL= [tab] Use the browser > > ## Step 3. Create a Vercel project > > 1. From the [Vercel dashboard](https://vercel.com/dashboard), click **Add new\...** > **Project**. > 2. Select the `prisma-examples` repository you forked in [Step 2](#step-2-get-the-code) to import. > 3. From the **Framework preset** dropdown, select **Next.js**. > 4. In the **Root directory** field, click **Edit**. > 5. Select the **typescript** > **rest-nextjs-api-routes** directory. > 6. Click **Continue**. > 7. Open the **Build and Output Settings** and toggle the build command's **Override** switch to on. > 8. Enter `yarn prisma db push && yarn next build` as the **Build command**. > 9. Click **Deploy**. > > Your deployment will fail until you integrate CockroachDB in the next step, so you can leave this screen without waiting for it to finish. > > ## Step 4. Integrate your project with CockroachDB > > 1. Navigate to the [CockroachDB page](https://vercel.com/integrations/cockroachdb) of Vercel's integration marketplace. > 2. Click **Add Integration**. > 3. Select your Vercel account and click **Continue**. > 4. Select the project you just created and click **Continue**. > 5. Accept the permissions and click **Add Integration**. > 6. When prompted, log into CockroachDB Cloud and select the organization and cluster to integrate with. > 7. Click **Create** to finish the integration. > > After a few seconds, the window will close automatically and your Vercel project will have the `DATABASE_URL` environment variable configured with the cluster's connection string. > > ## Step 5. Deploy the application > > 1. Navigate to the **Overview** page for your Vercel project. > 2. Select the **Deployments** tab. > 3. Click **Redeploy**. > 4. Click **Redeploy** again from the pop-up dialog. > > Your project will be deployed in a few seconds. You can view the final product by clicking on the **Domain** link on your project's **Overview** page. > [tab] Use the command line > > ## Step 3. Initialize the database > > 1. Save [the connection string](#connection-string) you obtained earlier from the CockroachDB Cloud Console to the `DATABASE_URL` environment variable in an `.env` file in your project: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > echo "DATABASE_URL=> .env > ``` > > Prisma loads the variables defined in `.env` to the project environment. By default, Prisma uses the `DATABASE_URL` environment variable as the connection string to the database. > > 2. Run [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate) to initialize the database with the schema defined in `prisma/prisma.schema`. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > prisma migrate dev --name init > ``` > > You should see the following output: > > ``` > Your database is now in sync with your schema. > > ✔ Generated Prisma Client (3.11.0 | library) to ./node_modules/@prisma/client in 87ms > ``` > > This command also initializes [Prisma Client](https://www.prisma.io/docs/concepts/components/prisma-client) to communicate with your CockroachDB cluster, based on the configuration in the `prisma/schema.prisma` file. > > ## Step 4. Deploy the application > > 1. (Optional) Run the app server locally to preview your site: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > npm run dev > ``` > > You should see the following output: > > ``` > ready - started server on 0.0.0.0:3000, url: http://localhost:3000 > ``` > > 2. Run the `vercel` command to start deploying the app: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > vercel deploy --confirm > ``` > > You will be asked to sign into your Vercel account. When you authenticate your credentials, you should see the following message: > > ``` > > Success! GitHub authentication complete ... > ``` > > The [`--confirm` flag](https://vercel.com/docs/cli#introduction/unique-options/confirm) instructs Vercel to deploy the app to the `example-app-typescript-vercel` Vercel project, using the default settings: > > ``` > 🔗 Linked to username/example-app-typescript-vercel (created .vercel and added it to .gitignore) > 🔍 Inspect: https://vercel.com/username/example-app-typescript-vercel/123456789 [1s] > ✅ Production: https://example-app-typescript-vercel-username.vercel.app [copied to clipboard] [47s] > 📝 Deployed to production. Run `vercel --prod` to overwrite later (https://vercel.link/2F). > 💡 To change the domain or build command, go to https://vercel.com/ericharmeling/example-app-typescript-vercel/settings > ``` > > Follow the links provided to view and manage your deployed application. ## See also * [Vercel's official How to Build a Fullstack App with Next.js, Prisma, and PostgreSQL guide](https://vercel.com/guides/nextjs-prisma-postgres) * [How to build a Complete Webapp with React, TypeScript & CockroachDB](https://www.cockroachlabs.com/blog/react-typescript-cockroachdb-sample-app/#deploy-the-application-to-netlify) * [Build a Simple CRUD Node.js App with CockroachDB and Prisma Client](/docs/v26.4/build-a-nodejs-app-with-cockroachdb-prisma) You might also be interested in the following pages: * [Client Connection Parameters](/docs/v26.4/connection-parameters) * [Connection Pooling](/docs/v26.4/connection-pooling) * [Data Replication](/docs/v26.4/demo-replication-and-rebalancing) * [CockroachDB Resilience](/docs/v26.4/demo-cockroachdb-resilience) * [Replication & Rebalancing](/docs/v26.4/demo-replication-and-rebalancing) # Deploy CockroachDB on AWS EC2 Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-on-aws This page shows you how to manually deploy a multi-node, self-hosted CockroachDB cluster on Amazon's AWS EC2 platform, using AWS's managed load-balancing service to distribute client traffic. After setting up the AWS network, clock synchronization, and load balancing, it should take approximately 20 minutes to complete the deployment. This is based on initializing a three-node CockroachDB cluster in a single AWS region and running our sample workload. If you are only testing CockroachDB, or you are not concerned with protecting network communication with TLS encryption, you can use an insecure cluster instead. Select **Insecure** above for instructions. > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. > [!NOTE] > > You need a license to use CockroachDB. Refer to the [Licensing FAQ](/docs/v26.4/licensing-faqs) and [CockroachDB Pricing](https://www.cockroachlabs.com/pricing). [Contact us](https://cockroachlabs.com/contact-sales) about custom pricing through AWS Marketplace. ## Before you begin ### Requirements * You must have [CockroachDB installed](/docs/v26.4/install-cockroachdb-mac) locally. This is necessary for generating and managing your deployment's certificates. * You must have [SSH access]() to each machine. This is necessary for distributing and starting CockroachDB binaries. * Your network configuration must allow TCP communication on the following ports: * `26257` for intra-cluster and client-cluster communication * `8080` to expose your DB Console * Carefully review the [Production Checklist](/docs/v26.4/recommended-production-settings), including supported hardware and software, and the recommended [Topology Patterns](/docs/v26.4/topology-patterns). * Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine. * To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see [Start a Node](/docs/v26.4/cockroach-start#store). If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`. * When starting each node, use the [`--locality`](/docs/v26.4/cockroach-start#locality) flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes. * When deploying in a single availability zone: * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the [`default` 3-way replication factor](/docs/v26.4/configure-replication-zones#view-the-default-replication-zone). In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority. * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and [increase the `default` replication factor for user data](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to 5. The replication factor for [important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority. * When deploying across multiple availability zones: * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas. * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption. * When deploying across multiple regions: * To be able to tolerate the failure of 1 entire region, use at least 3 regions. > [!NOTE] > > CockroachDB is supported in all [AWS regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html). ### Recommendations * Decide how you want to access your DB Console: | Access Level | Description | | - | - | | Partially open | Set a firewall rule to allow only specific IP addresses to communicate on port `8080`. | | Completely open | Set a firewall rule to allow all IP addresses to communicate on port `8080`. | | Completely closed | Set a firewall rule to disallow all communication on port `8080`. In this case, a machine with SSH access to a node could use an SSH tunnel to access the DB Console. | * You should have familiarity with configuring the following AWS components: * [Amazon VPC](https://docs.aws.amazon.com/vpc/index.html) * [Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) * [Internet gateways](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) * [Route tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) * [AWS VPN](https://aws.amazon.com/vpn/) * [Virtual private gateways](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) * [Elastic Load Balancing](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/load-balancer-types.html) * All Amazon EC2 instances running CockroachDB should be members of the same [security group](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). For an example, see [AWS architecture](#aws-architecture). * Follow the [AWS IAM best practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) to harden the AWS environment. Use [roles](/docs/v26.4/security-reference/authorization#roles) to grant access to the deployment, following a [policy of least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). * The [AWS root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) is *not* necessary. * Review the [AWS Config service limits](https://docs.aws.amazon.com/config/latest/developerguide/configlimits.html) and contact AWS support to request a quota increase, if necessary. ### AWS architecture In this basic deployment, 3 CockroachDB nodes are each deployed on an Amazon EC2 instance across 3 availability zones. These are grouped within a single VPC and security group. Users are routed to the cluster via [Amazon Route 53](https://aws.amazon.com/route53/) (which is not used in this tutorial) and a load balancer. ![Architecture diagram for a three-node CockroachDB cluster deployed on AWS](https://mintcdn.com/cockroachlabs/Vnu3Mn2DzHS7Vfry/images/common/aws-architecture.png?fit=max\&auto=format\&n=Vnu3Mn2DzHS7Vfry\&q=85\&s=5e7590683ff022315bd4449b5fbe2c11) ## Step 1. Create instances Open the [Amazon EC2 console](https://console.aws.amazon.com/ec2/) and [launch an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/launching-instance.html#launch-instance-console) for each node you plan to have in your cluster. If you plan to [run our sample workload](#step-9-run-a-sample-workload) against the cluster, create a separate instance for that workload. * Run at least 3 nodes to ensure survivability. * Your instances will rely on Amazon Time Sync Service for clock synchronization. When choosing an AMI, note that some machines are preconfigured to use Amazon Time Sync Service (e.g., Amazon Linux AMIs) and others are not. * Use general-purpose [`m6i` or `m6a`](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/general-purpose-instances.html) VMs with SSD-backed [EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html). For example, Cockroach Labs has used `m6i.2xlarge` for performance benchmarking. If your workload requires high throughput, use network-optimized `m5n` instances. To simulate bare-metal deployments, use `m5d` with [SSD Instance Store volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ssd-instance-store.html). * `m5` and `m5a` instances, and [compute-optimized `c5`, `c5a`, and `c5n`](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/compute-optimized-instances.html) instances, are also acceptable. > [!CAUTION] > > **Do not** use [burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html), which limit the load on a single core. * Note the ID of the VPC you select. You will need to look up its IP range when setting inbound rules for your security group. * Make sure all your instances are in the same security group. * If you are creating a new security group, add the [inbound rules](#step-2-configure-your-network) from the next step. Otherwise note the ID of the security group. * When creating the instance, you will be prompted to specify an EC2 key pair. For more information on key pairs, see the [AWS documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html). These are used to securely connect to your instances and should be encrypted (e.g., `ssh-keygen -p -f $keypairfile` in Linux). For more details, see [Hardware Recommendations](/docs/v26.4/recommended-production-settings#hardware) and [Cluster Topology](/docs/v26.4/recommended-production-settings#topology). ## Step 2. Configure your network [Add Custom TCP inbound rules](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html#adding-security-group-rule) to your security group to allow TCP communication on two ports: * `26257` for inter-node and client-node communication. This enables the nodes to work as a cluster, the load balancer to route traffic to the nodes, and applications to connect to the load balancer. * `8080` for exposing the DB Console to the user, and for routing the load balancer to the health check endpoint. #### Inter-node and load balancer-node communication | Field | Value | | - | - | | Port Range | **26257** | | Source | The ID of your security group (e.g., *sg-07ab277a*) | #### Application data | Field | Value | | - | - | | Port Range | **26257** | | Source | Your application's IP ranges | #### DB Console | Field | Value | | - | - | | Port Range | **8080** | | Source | Your network's IP ranges | You can set your network IP by selecting "My IP" in the Source field. #### Load balancer-health check communication | Field | Value | | - | - | | Port Range | **8080** | | Source | The IP range of your VPC in CIDR notation (e.g., 10.12.0.0/16) | To get the IP range of a VPC, open the [Amazon VPC console](https://console.aws.amazon.com/vpc/) and find the VPC listed in the section called Your VPCs. #### Load balancer-health check communication | Field | Value | | - | - | | Port Range | **8080** | | Source | The IP range of your VPC in CIDR notation (e.g., 10.12.0.0/16) | To get the IP range of a VPC, open the [Amazon VPC console](https://console.aws.amazon.com/vpc/) and find the VPC listed in the section called Your VPCs. ## Step 3. Synchronize clocks CockroachDB requires moderate levels of [clock synchronization](/docs/v26.4/recommended-production-settings#clock-synchronization) to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed (500ms by default), it spontaneously shuts down. This avoids the risk of consistency anomalies, but it's best to prevent clocks from drifting too far in the first place by running clock synchronization software on each node. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well. 1. SSH to the first machine. 2. Disable `timesyncd`, which tends to be active by default on some Linux distributions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo timedatectl set-ntp no ``` Verify that `timesyncd` is off: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ timedatectl ``` Look for `Network time on: no` or `NTP enabled: no` in the output. 3. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 4. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 5. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` > [!NOTE] > > We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 1. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 2. Repeat these steps for each machine where a CockroachDB node will run. Compute Engine instances are preconfigured to use [NTP](http://www.ntp.org/), which should keep offsets in the single-digit milliseconds. However, Google can’t predict how external NTP services, such as `pool.ntp.org`, will handle the leap second. Therefore, you should: * [Configure each GCE instance to use Google's internal NTP service](https://cloud.google.com/compute/docs/instances/configure-ntp#configure_ntp_for_your_instances). * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. Amazon provides the [Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html), which uses a fleet of satellite-connected and atomic reference clocks in each AWS Region to deliver accurate current time readings. The service also smears the leap second. * [Configure each AWS instance to use the internal Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure-amazon-time-service). * Per the above instructions, ensure that `etc/chrony.conf` on the instance contains the line `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` and that other `server` or `pool` lines are commented out. * To verify that Amazon Time Sync Service is being used, run `chronyc sources -v` and check for a line containing `* 169.254.169.123`. The `*` denotes the preferred time server. * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here. However, to run `ntpd` properly on Azure VMs, it's necessary to first unbind the Time Synchronization device used by the Hyper-V technology running Azure VMs; this device aims to synchronize time between the VM and its host operating system but has been known to cause problems. 1. SSH to the first machine. 2. Find the ID of the Hyper-V Time Synchronization device: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/lsvmbus ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python lsvmbus -vv | grep -w "Time Synchronization" -A 3 ``` ``` VMBUS ID 12: Class_ID = {9527e630-d0ae-497b-adce-e80ab0175caf} - [Time Synchronization] Device_ID = {2dd1ce17-079e-403c-b352-a1921ee207ee} Sysfs path: /sys/bus/vmbus/devices/2dd1ce17-079e-403c-b352-a1921ee207ee Rel_ID=12, target_cpu=0 ``` 3. Unbind the device, using the `Device_ID` from the previous command's output: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo | sudo tee /sys/bus/vmbus/drivers/hv_utils/unbind ``` 4. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 5. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 6. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 7. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 8. Repeat these steps for each machine where a CockroachDB node will run. ## Step 4. Set up load balancing Each CockroachDB node is an equally suitable SQL gateway to your cluster, but to ensure client performance and reliability, it's important to use load balancing: * **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second). * **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. In cases where a node fails, the load balancer redirects client traffic to available nodes. AWS offers fully-managed load balancing to distribute traffic between instances. 1. [Add AWS load balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancer-getting-started.html). Be sure to: * Select a **Network Load Balancer** and use the ports we specify below. * Select the VPC and *all* availability zones of your instances. This is important, as you cannot change the availability zones once the load balancer is created. The availability zone of an instance is determined by its subnet, found by inspecting the instance in the Amazon EC2 Console. * Set the load balancer port to **26257**. * Create a new target group that uses TCP port **26257**. Traffic from your load balancer is routed to this target group, which contains your instances. * Configure health checks to use HTTP port **8080** and path `/health?ready=1`. This [health endpoint](/docs/v26.4/monitoring-and-alerting) ensures that load balancers do not direct traffic to nodes that are live but not ready to receive requests. * Register your instances with the target group you created, specifying port **26257**. You can add and remove instances later. 2. To test load balancing and connect your application to the cluster, you will need the provisioned internal (private) **IP address** for the load balancer. To find this, open the Network Interfaces section of the Amazon EC2 console and look up the load balancer by its name. ## Step 5. Generate certificates You can use `cockroach cert` commands or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to generate security certificates. This section features the `cockroach cert` commands. Locally, you'll need to [create the following certificates and keys](/docs/v26.4/cockroach-cert): * A certificate authority (CA) key pair (`ca.crt` and `ca.key`). * A node key pair for each node, issued to its IP addresses and any common names the machine uses, as well as to the IP addresses and common names for machines running load balancers. * A client key pair for the `root` user. You'll use this to run a sample workload against the cluster as well as some `cockroach` client commands from your local machine. 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac) on your local machine, if you haven't already. 2. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir my-safe-directory ``` * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes. * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. After that, you'll keep the key safe and secret; you will not upload it to your nodes. 3. Create the CA certificate and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Create the certificate and key for the first node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 5. Upload the CA certificate and node certificate and key to the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud compute ssh \ --project \ --command "mkdir certs" ``` > [!NOTE] > > `gcloud compute ssh` associates your public SSH key with the GCP project and is only needed when connecting to the first node. See the [GCP docs](https://cloud.google.com/sdk/gcloud/reference/compute/ssh) for more details. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ @@@@@ [!NOTE] > > This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key`. As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag. 1. Create the certificate and key for the second node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 2. Upload the CA certificate and node certificate and key to the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ssh @@@@@@ [!NOTE] > > On accessing the DB Console in a later step, your browser will consider the CockroachDB-created certificate invalid and you’ll need to click through a warning message to get to the UI. You can avoid this issue by [using a certificate issued by a public CA](/docs/v26.4/create-security-certificates-custom-ca#accessing-the-db-console-for-a-secure-cluster). ## Step 6. Start nodes You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each initial node of your cluster, complete the following steps: > > > [!NOTE] > > > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. Visit [Releases](/docs/releases/index) and download the full binary of CockroachDB to the node. > > 2. On the node, follow the instructions to [install CockroachDB](/docs/v26.4/install-cockroachdb-mac). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > This command primes the node to start, using the following flags: > > | Flag | Description | > | - | - | > | `--certs-dir` | Specifies the directory where you placed the `ca.crt` file and the `node.crt` and `node.key` files for the node. | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > | `--cache` `--max-sql-memory` | Increases the node's cache size to 25% of available system memory to improve read performance. The capacity for in-memory SQL processing defaults to 25% of system memory but can be raised, if necessary, to increase the number of simultaneous client connections allowed by the node as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. For more details, see [Cache and SQL Memory Size](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). | > | `--background` | Starts the node in the background so you gain control of the terminal to issue more commands. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr= > Repeat these steps for each additional node that you want in your cluster. > [tab] systemd > > For each initial node of your cluster, complete the following steps: > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ chown -R cockroach /var/lib/cockroach > ``` > > 7. Save the following sample configuration template as `/etc/systemd/system/securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > 8. In the sample configuration template, specify values for the following flags: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=localhost:8080`. To set these options manually, see [Start a Node](/docs/v26.4/cockroach-start#standard-output). > > 9. Start the CockroachDB cluster: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl start securecockroachdb > ``` > > 10. Configure `systemd` to start CockroachDB automatically after a reboot: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl enable securecockroachdb > ``` > > 11. Repeat these steps for each additional node that you want in your cluster. > > > [!NOTE] > > > > `systemd` handles node restarts in case of node failure. To stop a node without `systemd` restarting it, run `systemctl stop securecockroachdb` ## Step 7. Initialize the cluster On your local machine, run the [`cockroach init`](/docs/v26.4/cockroach-init) command to complete the node startup process and have them join together as a cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --certs-dir=certs --host=
CREATE DATABASE securenodetest; ``` 3. View the cluster's databases, which will include `securenodetest`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW DATABASES; ``` ``` +--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | securenodetest | | pg_catalog | | system | +--------------------+ (5 rows) ``` 4. Use `\q` to exit the SQL shell. ## Step 9. Run a sample workload CockroachDB comes with a number of [built-in workloads](/docs/v26.4/cockroach-workload) for simulating client traffic. This step features CockroachDB's version of the [TPC-C](http://www.tpc.org/tpcc/) workload. > [!NOTE] > > Be sure that you have configured your network to allow traffic from the application to the load balancer. In this case, you will run the sample workload on one of your machines. The traffic source should therefore be the **internal (private)** IP address of that machine. 1. SSH to the machine where you want to run the sample TPC-C workload. This should be a machine that is not running a CockroachDB node, and it should already have a `certs` directory containing `ca.crt`, `client.root.crt`, and `client.root.key` files. 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). 3. Use the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to load the initial schema and data, pointing it at the IP address of the load balancer: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload init tpcc \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` 4. Use the `cockroach workload` command to run the workload for 10 minutes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload run tpcc \ --duration=10m \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` You'll see per-operation statistics print to standard output every second: ``` _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms) 1s 0 1443.4 1494.8 4.7 9.4 27.3 67.1 transfer 2s 0 1686.5 1590.9 4.7 8.1 15.2 28.3 transfer 3s 0 1735.7 1639.0 4.7 7.3 11.5 28.3 transfer 4s 0 1542.6 1614.9 5.0 8.9 12.1 21.0 transfer 5s 0 1695.9 1631.1 4.7 7.3 11.5 22.0 transfer 6s 0 1569.2 1620.8 5.0 8.4 11.5 15.7 transfer 7s 0 1614.6 1619.9 4.7 8.1 12.1 16.8 transfer 8s 0 1344.4 1585.6 5.8 10.0 15.2 31.5 transfer 9s 0 1351.9 1559.5 5.8 10.0 16.8 54.5 transfer 10s 0 1514.8 1555.0 5.2 8.1 12.1 16.8 transfer ... ``` After the specified duration (10 minutes in this case), the workload will stop and you'll see totals printed to standard output: ``` _elapsed___errors_____ops(total)___ops/sec(cum)__avg(ms)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)__result 600.0s 0 823902 1373.2 5.8 5.5 10.0 15.2 209.7 ``` > [!TIP] > > For more `tpcc` options, use `cockroach workload run tpcc --help`. For details about other workloads built into the `cockroach` binary, use `cockroach workload --help`. 1. To monitor the load generator's progress, open the [DB Console](/docs/v26.4/ui-overview) by pointing a browser to the address in the `admin` field in the standard output of any node on startup. Since the load generator is pointed at the load balancer, the connections will be evenly distributed across nodes. To verify this, click **Metrics** on the left, select the **SQL** dashboard, and then check the **SQL Connections** graph. You can use the **Graph** menu to filter the graph for specific nodes. ## Step 10. Monitor the cluster In the Target Groups section of the Amazon EC2 console, [check the health](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-health-checks.html) of your instances by inspecting your target group and opening the Targets tab. Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. For details about available monitoring options and the most important events and metrics to alert on, see [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting). ## Step 11. Scale the cluster Before adding a new node, [create a new instance](#step-1-create-instances) as you did earlier. Then [generate and upload a certificate and key](#step-5-generate-certificates) for the new node. You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command, passing the new node's address as the `--advertise-addr` flag and pointing `--join` to the three existing nodes (also include `--locality` if you set it earlier). > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > 4. Update your load balancer to recognize the new node. > [tab] systemd > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > chown -R cockroach /var/lib/cockroach > ``` > > 7. Copy the following sample configuration template into a file named `securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > Save the file in the `/etc/systemd/system/` directory. > > 8. Customize the sample configuration template for your deployment: > > Specify values for the following flags in the sample configuration template: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > 9. Repeat these steps for each additional node that you want in your cluster. ## Step 12. Use the database Now that your deployment is working, you can: 1. [Implement your data model](/docs/v26.4/sql-statements). 2. [Create users](/docs/v26.4/create-user) and [grant them privileges](/docs/v26.4/grant). 3. [Connect your application](/docs/v26.4/install-client-drivers). Be sure to connect your application to the load balancer, not to a CockroachDB node. 4. [Take backups](/docs/v26.4/take-full-and-incremental-backups) of your data. You may also want to adjust the way the cluster replicates data. For example, by default, a multi-node cluster replicates all data 3 times; you can change this replication factor or create additional rules for replicating individual databases and tables differently. For more information, see [Replication Controls](/docs/v26.4/configure-replication-zones). > [!CAUTION] > > When running a cluster of 5 nodes or more, it's safest to [increase the replication factor for important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) to 5, even if you do not do so for user data. For the cluster as a whole to remain available, the ranges for this internal data must always retain a majority of their replicas. ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Performance Tuning](/docs/v26.4/performance-best-practices-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Deploy CockroachDB on Digital Ocean Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-on-digital-ocean This page shows you how to deploy a secure multi-node CockroachDB cluster on Digital Ocean, using Digital Ocean's managed load balancing service to distribute client traffic. If you are only testing CockroachDB, or you are not concerned with protecting network communication with TLS encryption, you can use an insecure cluster instead. Select **Insecure** above for instructions. > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. ## Before you begin ### Requirements * You must have [CockroachDB installed](/docs/v26.4/install-cockroachdb-mac) locally. This is necessary for generating and managing your deployment's certificates. * You must have [SSH access]() to each machine. This is necessary for distributing and starting CockroachDB binaries. * Your network configuration must allow TCP communication on the following ports: * `26257` for intra-cluster and client-cluster communication * `8080` to expose your DB Console * Carefully review the [Production Checklist](/docs/v26.4/recommended-production-settings), including supported hardware and software, and the recommended [Topology Patterns](/docs/v26.4/topology-patterns). * Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine. * To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see [Start a Node](/docs/v26.4/cockroach-start#store). If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`. * When starting each node, use the [`--locality`](/docs/v26.4/cockroach-start#locality) flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes. * When deploying in a single availability zone: * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the [`default` 3-way replication factor](/docs/v26.4/configure-replication-zones#view-the-default-replication-zone). In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority. * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and [increase the `default` replication factor for user data](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to 5. The replication factor for [important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority. * When deploying across multiple availability zones: * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas. * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption. * When deploying across multiple regions: * To be able to tolerate the failure of 1 entire region, use at least 3 regions. ### Recommendations * Decide how you want to access your DB Console: | Access Level | Description | | - | - | | Partially open | Set a firewall rule to allow only specific IP addresses to communicate on port `8080`. | | Completely open | Set a firewall rule to allow all IP addresses to communicate on port `8080`. | | Completely closed | Set a firewall rule to disallow all communication on port `8080`. In this case, a machine with SSH access to a node could use an SSH tunnel to access the DB Console. | * If all of your CockroachDB nodes and clients will run on Droplets in a single region, consider using [private networking](https://docs.digitalocean.com/products/networking/vpc/how-to/create/). ## Step 1. Create Droplets [Create Droplets](https://www.digitalocean.com/community/tutorials/how-to-create-your-first-digitalocean-droplet) for each node you plan to have in your cluster. If you plan to run a sample workload against the cluster, create a separate Droplet for that workload. * Run at least 3 nodes to [ensure survivability](/docs/v26.4/recommended-production-settings#topology). * Use any [droplets](https://www.digitalocean.com/pricing/) except standard droplets with only 1 GB of RAM, which is below our minimum requirement. All Digital Ocean droplets use SSD storage. For more details, see [Hardware Recommendations](/docs/v26.4/recommended-production-settings#hardware) and [Cluster Topology](/docs/v26.4/recommended-production-settings#topology). ## Step 2. Synchronize clocks CockroachDB requires moderate levels of [clock synchronization](/docs/v26.4/recommended-production-settings#clock-synchronization) to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed (500ms by default), it spontaneously shuts down. This avoids the risk of consistency anomalies, but it's best to prevent clocks from drifting too far in the first place by running clock synchronization software on each node. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well. 1. SSH to the first machine. 2. Disable `timesyncd`, which tends to be active by default on some Linux distributions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo timedatectl set-ntp no ``` Verify that `timesyncd` is off: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ timedatectl ``` Look for `Network time on: no` or `NTP enabled: no` in the output. 3. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 4. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 5. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` > [!NOTE] > > We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 1. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 2. Repeat these steps for each machine where a CockroachDB node will run. Compute Engine instances are preconfigured to use [NTP](http://www.ntp.org/), which should keep offsets in the single-digit milliseconds. However, Google can’t predict how external NTP services, such as `pool.ntp.org`, will handle the leap second. Therefore, you should: * [Configure each GCE instance to use Google's internal NTP service](https://cloud.google.com/compute/docs/instances/configure-ntp#configure_ntp_for_your_instances). * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. Amazon provides the [Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html), which uses a fleet of satellite-connected and atomic reference clocks in each AWS Region to deliver accurate current time readings. The service also smears the leap second. * [Configure each AWS instance to use the internal Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure-amazon-time-service). * Per the above instructions, ensure that `etc/chrony.conf` on the instance contains the line `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` and that other `server` or `pool` lines are commented out. * To verify that Amazon Time Sync Service is being used, run `chronyc sources -v` and check for a line containing `* 169.254.169.123`. The `*` denotes the preferred time server. * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here. However, to run `ntpd` properly on Azure VMs, it's necessary to first unbind the Time Synchronization device used by the Hyper-V technology running Azure VMs; this device aims to synchronize time between the VM and its host operating system but has been known to cause problems. 1. SSH to the first machine. 2. Find the ID of the Hyper-V Time Synchronization device: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/lsvmbus ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python lsvmbus -vv | grep -w "Time Synchronization" -A 3 ``` ``` VMBUS ID 12: Class_ID = {9527e630-d0ae-497b-adce-e80ab0175caf} - [Time Synchronization] Device_ID = {2dd1ce17-079e-403c-b352-a1921ee207ee} Sysfs path: /sys/bus/vmbus/devices/2dd1ce17-079e-403c-b352-a1921ee207ee Rel_ID=12, target_cpu=0 ``` 3. Unbind the device, using the `Device_ID` from the previous command's output: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo | sudo tee /sys/bus/vmbus/drivers/hv_utils/unbind ``` 4. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 5. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 6. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 7. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 8. Repeat these steps for each machine where a CockroachDB node will run. ## Step 3. Set up load balancing Each CockroachDB node is an equally suitable SQL gateway to your cluster, but to ensure client performance and reliability, it's important to use load balancing: * **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second). * **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. In cases where a node fails, the load balancer redirects client traffic to available nodes. Digital Ocean offers fully-managed load balancers to distribute traffic between Droplets. 1. [Create a Digital Ocean Load Balancer](https://www.digitalocean.com/community/tutorials/an-introduction-to-digitalocean-load-balancers). Be sure to: * Set forwarding rules to route TCP traffic from the load balancer's port **26257** to port **26257** on the node Droplets. * Configure health checks to use HTTP port **8080** and path `/health?ready=1`. This [health endpoint](/docs/v26.4/monitoring-and-alerting) ensures that load balancers do not direct traffic to nodes that are live but not ready to receive requests. 2. Note the provisioned **IP Address** for the load balancer. You'll use this later to test load balancing and to connect your application to the cluster. ## Step 4. Configure your network Set up a firewall for each of your Droplets, allowing TCP communication on the following two ports: * **26257** (`tcp:26257`) for inter-node communication (i.e., working as a cluster), for applications to connect to the load balancer, and for routing from the load balancer to nodes * **8080** (`tcp:8080`) for exposing your DB Console For guidance, you can use Digital Ocean's guide to configuring firewalls based on the Droplet's OS: * Ubuntu and Debian can use [`ufw`](https://www.digitalocean.com/community/tutorials/how-to-setup-a-firewall-with-ufw-on-an-ubuntu-and-debian-cloud-server). * FreeBSD can use [`ipfw`](https://www.digitalocean.com/community/tutorials/recommended-steps-for-new-freebsd-10-1-servers). * Fedora can use [`iptables`](https://www.digitalocean.com/community/tutorials/initial-setup-of-a-fedora-22-server). * CoreOS can use [`iptables`](https://www.digitalocean.com/community/tutorials/how-to-secure-your-coreos-cluster-with-tls-ssl-and-firewall-rules). * CentOS can use [`firewalld`](https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7). ## Step 5. Generate certificates You can use `cockroach cert` commands or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to generate security certificates. This section features the `cockroach cert` commands. Locally, you'll need to [create the following certificates and keys](/docs/v26.4/cockroach-cert): * A certificate authority (CA) key pair (`ca.crt` and `ca.key`). * A node key pair for each node, issued to its IP addresses and any common names the machine uses, as well as to the IP addresses and common names for machines running load balancers. * A client key pair for the `root` user. You'll use this to run a sample workload against the cluster as well as some `cockroach` client commands from your local machine. 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac) on your local machine, if you haven't already. 2. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir my-safe-directory ``` * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes. * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. After that, you'll keep the key safe and secret; you will not upload it to your nodes. 3. Create the CA certificate and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Create the certificate and key for the first node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 5. Upload the CA certificate and node certificate and key to the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud compute ssh \ --project \ --command "mkdir certs" ``` > [!NOTE] > > `gcloud compute ssh` associates your public SSH key with the GCP project and is only needed when connecting to the first node. See the [GCP docs](https://cloud.google.com/sdk/gcloud/reference/compute/ssh) for more details. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ @@@@@ [!NOTE] > > This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key`. As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag. 1. Create the certificate and key for the second node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 2. Upload the CA certificate and node certificate and key to the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ssh @@@@@@ [!NOTE] > > On accessing the DB Console in a later step, your browser will consider the CockroachDB-created certificate invalid and you’ll need to click through a warning message to get to the UI. You can avoid this issue by [using a certificate issued by a public CA](/docs/v26.4/create-security-certificates-custom-ca#accessing-the-db-console-for-a-secure-cluster). ## Step 6. Start nodes You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each initial node of your cluster, complete the following steps: > > > [!NOTE] > > > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. Visit [Releases](/docs/releases/index) and download the full binary of CockroachDB to the node. > > 2. On the node, follow the instructions to [install CockroachDB](/docs/v26.4/install-cockroachdb-mac). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > This command primes the node to start, using the following flags: > > | Flag | Description | > | - | - | > | `--certs-dir` | Specifies the directory where you placed the `ca.crt` file and the `node.crt` and `node.key` files for the node. | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > | `--cache` `--max-sql-memory` | Increases the node's cache size to 25% of available system memory to improve read performance. The capacity for in-memory SQL processing defaults to 25% of system memory but can be raised, if necessary, to increase the number of simultaneous client connections allowed by the node as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. For more details, see [Cache and SQL Memory Size](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). | > | `--background` | Starts the node in the background so you gain control of the terminal to issue more commands. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr= > Repeat these steps for each additional node that you want in your cluster. > [tab] systemd > > For each initial node of your cluster, complete the following steps: > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ chown -R cockroach /var/lib/cockroach > ``` > > 7. Save the following sample configuration template as `/etc/systemd/system/securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > 8. In the sample configuration template, specify values for the following flags: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=localhost:8080`. To set these options manually, see [Start a Node](/docs/v26.4/cockroach-start#standard-output). > > 9. Start the CockroachDB cluster: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl start securecockroachdb > ``` > > 10. Configure `systemd` to start CockroachDB automatically after a reboot: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl enable securecockroachdb > ``` > > 11. Repeat these steps for each additional node that you want in your cluster. > > > [!NOTE] > > > > `systemd` handles node restarts in case of node failure. To stop a node without `systemd` restarting it, run `systemctl stop securecockroachdb` ## Step 7. Initialize the cluster On your local machine, run the [`cockroach init`](/docs/v26.4/cockroach-init) command to complete the node startup process and have them join together as a cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --certs-dir=certs --host=
CREATE DATABASE securenodetest; ``` 3. View the cluster's databases, which will include `securenodetest`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW DATABASES; ``` ``` +--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | securenodetest | | pg_catalog | | system | +--------------------+ (5 rows) ``` 4. Use `\q` to exit the SQL shell. ## Step 9. Run a sample workload CockroachDB comes with a number of [built-in workloads](/docs/v26.4/cockroach-workload) for simulating client traffic. This step features CockroachDB's version of the [TPC-C](http://www.tpc.org/tpcc/) workload. > [!NOTE] > > Be sure that you have configured your network to allow traffic from the application to the load balancer. In this case, you will run the sample workload on one of your machines. The traffic source should therefore be the **internal (private)** IP address of that machine. 1. SSH to the machine where you want to run the sample TPC-C workload. This should be a machine that is not running a CockroachDB node, and it should already have a `certs` directory containing `ca.crt`, `client.root.crt`, and `client.root.key` files. 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). 3. Use the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to load the initial schema and data, pointing it at the IP address of the load balancer: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload init tpcc \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` 4. Use the `cockroach workload` command to run the workload for 10 minutes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload run tpcc \ --duration=10m \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` You'll see per-operation statistics print to standard output every second: ``` _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms) 1s 0 1443.4 1494.8 4.7 9.4 27.3 67.1 transfer 2s 0 1686.5 1590.9 4.7 8.1 15.2 28.3 transfer 3s 0 1735.7 1639.0 4.7 7.3 11.5 28.3 transfer 4s 0 1542.6 1614.9 5.0 8.9 12.1 21.0 transfer 5s 0 1695.9 1631.1 4.7 7.3 11.5 22.0 transfer 6s 0 1569.2 1620.8 5.0 8.4 11.5 15.7 transfer 7s 0 1614.6 1619.9 4.7 8.1 12.1 16.8 transfer 8s 0 1344.4 1585.6 5.8 10.0 15.2 31.5 transfer 9s 0 1351.9 1559.5 5.8 10.0 16.8 54.5 transfer 10s 0 1514.8 1555.0 5.2 8.1 12.1 16.8 transfer ... ``` After the specified duration (10 minutes in this case), the workload will stop and you'll see totals printed to standard output: ``` _elapsed___errors_____ops(total)___ops/sec(cum)__avg(ms)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)__result 600.0s 0 823902 1373.2 5.8 5.5 10.0 15.2 209.7 ``` > [!TIP] > > For more `tpcc` options, use `cockroach workload run tpcc --help`. For details about other workloads built into the `cockroach` binary, use `cockroach workload --help`. 1. To monitor the load generator's progress, open the [DB Console](/docs/v26.4/ui-overview) by pointing a browser to the address in the `admin` field in the standard output of any node on startup. Since the load generator is pointed at the load balancer, the connections will be evenly distributed across nodes. To verify this, click **Metrics** on the left, select the **SQL** dashboard, and then check the **SQL Connections** graph. You can use the **Graph** menu to filter the graph for specific nodes. ## Step 10. Monitor the cluster Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. For details about available monitoring options and the most important events and metrics to alert on, see [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting). ## Step 11. Scale the cluster You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command, passing the new node's address as the `--advertise-addr` flag and pointing `--join` to the three existing nodes (also include `--locality` if you set it earlier). > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > 4. Update your load balancer to recognize the new node. > [tab] systemd > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > chown -R cockroach /var/lib/cockroach > ``` > > 7. Copy the following sample configuration template into a file named `securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > Save the file in the `/etc/systemd/system/` directory. > > 8. Customize the sample configuration template for your deployment: > > Specify values for the following flags in the sample configuration template: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > 9. Repeat these steps for each additional node that you want in your cluster. ## Step 12. Use the database Now that your deployment is working, you can: 1. [Implement your data model](/docs/v26.4/sql-statements). 2. [Create users](/docs/v26.4/create-user) and [grant them privileges](/docs/v26.4/grant). 3. [Connect your application](/docs/v26.4/install-client-drivers). Be sure to connect your application to the load balancer, not to a CockroachDB node. 4. [Take backups](/docs/v26.4/take-full-and-incremental-backups) of your data. You may also want to adjust the way the cluster replicates data. For example, by default, a multi-node cluster replicates all data 3 times; you can change this replication factor or create additional rules for replicating individual databases and tables differently. For more information, see [Replication Controls](/docs/v26.4/configure-replication-zones). > [!CAUTION] > > When running a cluster of 5 nodes or more, it's safest to [increase the replication factor for important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) to 5, even if you do not do so for user data. For the cluster as a whole to remain available, the ranges for this internal data must always retain a majority of their replicas. ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Performance Tuning](/docs/v26.4/performance-best-practices-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Deploy CockroachDB on Google Cloud Platform GCE Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-on-google-cloud-platform This page shows you how to manually deploy a secure multi-node CockroachDB cluster on Google Cloud Platform's Compute Engine (GCE), using Google's TCP Proxy Load Balancing service to distribute client traffic. If you are only testing CockroachDB, or you are not concerned with protecting network communication with TLS encryption, you can use an insecure cluster instead. Select **Insecure** above for instructions. > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. ## Before you begin ### Requirements * You must have [CockroachDB installed](/docs/v26.4/install-cockroachdb-mac) locally. This is necessary for generating and managing your deployment's certificates. * You must have [SSH access]() to each machine. This is necessary for distributing and starting CockroachDB binaries. * Your network configuration must allow TCP communication on the following ports: * `26257` for intra-cluster and client-cluster communication * `8080` to expose your DB Console * Carefully review the [Production Checklist](/docs/v26.4/recommended-production-settings), including supported hardware and software, and the recommended [Topology Patterns](/docs/v26.4/topology-patterns). * Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine. * To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see [Start a Node](/docs/v26.4/cockroach-start#store). If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`. * When starting each node, use the [`--locality`](/docs/v26.4/cockroach-start#locality) flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes. * When deploying in a single availability zone: * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the [`default` 3-way replication factor](/docs/v26.4/configure-replication-zones#view-the-default-replication-zone). In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority. * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and [increase the `default` replication factor for user data](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to 5. The replication factor for [important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority. * When deploying across multiple availability zones: * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas. * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption. * When deploying across multiple regions: * To be able to tolerate the failure of 1 entire region, use at least 3 regions. * This article covers the use of Linux instances with GCE. You may wish to review the instructions for [connecting to Windows instances](https://cloud.google.com/compute/docs/instances/connecting-to-instance#windows). ### Recommendations * Decide how you want to access your DB Console: | Access Level | Description | | - | - | | Partially open | Set a firewall rule to allow only specific IP addresses to communicate on port `8080`. | | Completely open | Set a firewall rule to allow all IP addresses to communicate on port `8080`. | | Completely closed | Set a firewall rule to disallow all communication on port `8080`. In this case, a machine with SSH access to a node could use an SSH tunnel to access the DB Console. | ## Step 1. Configure your network CockroachDB requires TCP communication on two ports: * `26257` for inter-node communication (i.e., working as a cluster) * `8080` for exposing your DB Console To expose your DB Console and allow traffic from the TCP proxy load balancer and health checker to your instances, [create firewall rules](https://cloud.google.com/compute/docs/vpc/firewalls) for your project. When creating firewall rules, we recommend using Google Cloud Platform's **tag** feature to apply the rule only to instances with the same tag. #### DB Console | Field | Recommended Value | | - | - | | Name | **cockroachadmin** | | Source filter | IP ranges | | Source IP ranges | Your local network's IP ranges | | Allowed protocols... | **tcp:8080** | | Target tags | **cockroachdb** | #### Application data Applications will not connect directly to your CockroachDB nodes. Instead, they'll connect to GCE's TCP Proxy Load Balancing service, which automatically routes traffic to the instances that are closest to the user. Because this service is implemented at the edge of the Google Cloud, you'll need to create a firewall rule to allow traffic from the load balancer and health checker to your instances. This is covered in [Step 4](#step-4-set-up-load-balancing). ## Step 2. Create instances [Create an instance](https://cloud.google.com/compute/docs/instances/create-start-instance) for each node you plan to have in your cluster. If you plan to run a sample workload against the cluster, create a separate instance for that workload. * Run at least 3 nodes to [ensure survivability](/docs/v26.4/recommended-production-settings#topology). * Use general-purpose [`t2d-standard`, `n2-standard`, or `n2d-standard`](https://cloud.google.com/compute/pricing#predefined_machine_types) VMs, or use [custom VMs](https://cloud.google.com/compute/docs/instances/creating-instance-with-custom-machine-type). For example, Cockroach Labs has used `t2d-standard-8`, `n2-standard-8`, and `n2d-standard-8` for performance benchmarking. > [!CAUTION] > > Do not use `f1` or `g1` [shared-core machines](https://cloud.google.com/compute/docs/machine-types#sharedcore), which limit the load on CPU resources. * If you used a tag for your firewall rules, when you create the instance, click **Management, security, disks, networking, sole tenancy**. Under the **Networking** tab, in the **Network tags** field, enter **cockroachdb**. For more details, see [Hardware Recommendations](/docs/v26.4/recommended-production-settings#hardware) and [Cluster Topology](/docs/v26.4/recommended-production-settings#topology). ## Step 3. Synchronize clocks CockroachDB requires moderate levels of [clock synchronization](/docs/v26.4/recommended-production-settings#clock-synchronization) to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed (500ms by default), it spontaneously shuts down. This avoids the risk of consistency anomalies, but it's best to prevent clocks from drifting too far in the first place by running clock synchronization software on each node. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well. 1. SSH to the first machine. 2. Disable `timesyncd`, which tends to be active by default on some Linux distributions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo timedatectl set-ntp no ``` Verify that `timesyncd` is off: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ timedatectl ``` Look for `Network time on: no` or `NTP enabled: no` in the output. 3. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 4. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 5. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` > [!NOTE] > > We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 1. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 2. Repeat these steps for each machine where a CockroachDB node will run. Compute Engine instances are preconfigured to use [NTP](http://www.ntp.org/), which should keep offsets in the single-digit milliseconds. However, Google can’t predict how external NTP services, such as `pool.ntp.org`, will handle the leap second. Therefore, you should: * [Configure each GCE instance to use Google's internal NTP service](https://cloud.google.com/compute/docs/instances/configure-ntp#configure_ntp_for_your_instances). * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. Amazon provides the [Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html), which uses a fleet of satellite-connected and atomic reference clocks in each AWS Region to deliver accurate current time readings. The service also smears the leap second. * [Configure each AWS instance to use the internal Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure-amazon-time-service). * Per the above instructions, ensure that `etc/chrony.conf` on the instance contains the line `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` and that other `server` or `pool` lines are commented out. * To verify that Amazon Time Sync Service is being used, run `chronyc sources -v` and check for a line containing `* 169.254.169.123`. The `*` denotes the preferred time server. * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here. However, to run `ntpd` properly on Azure VMs, it's necessary to first unbind the Time Synchronization device used by the Hyper-V technology running Azure VMs; this device aims to synchronize time between the VM and its host operating system but has been known to cause problems. 1. SSH to the first machine. 2. Find the ID of the Hyper-V Time Synchronization device: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/lsvmbus ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python lsvmbus -vv | grep -w "Time Synchronization" -A 3 ``` ``` VMBUS ID 12: Class_ID = {9527e630-d0ae-497b-adce-e80ab0175caf} - [Time Synchronization] Device_ID = {2dd1ce17-079e-403c-b352-a1921ee207ee} Sysfs path: /sys/bus/vmbus/devices/2dd1ce17-079e-403c-b352-a1921ee207ee Rel_ID=12, target_cpu=0 ``` 3. Unbind the device, using the `Device_ID` from the previous command's output: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo | sudo tee /sys/bus/vmbus/drivers/hv_utils/unbind ``` 4. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 5. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 6. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 7. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 8. Repeat these steps for each machine where a CockroachDB node will run. ## Step 4. Set up load balancing Each CockroachDB node is an equally suitable SQL gateway to your cluster, but to ensure client performance and reliability, it's important to use load balancing: * **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second). * **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. In cases where a node fails, the load balancer redirects client traffic to available nodes. GCE offers fully-managed [TCP Proxy Load Balancing](https://cloud.google.com/load-balancing/docs/tcp/). This service lets you use a single IP address for all users around the world, automatically routing traffic to the instances that are closest to the user. > [!CAUTION] > > When using TCP Proxy Load Balancing, you cannot use firewall rules to control access to the load balancer. If you need such control, consider using [Network TCP Load Balancing](https://cloud.google.com/compute/docs/load-balancing/network/) instead, but note that it cannot be used across regions. You might also consider using the HAProxy load balancer (see the [On-Premises](/docs/v26.4/deploy-cockroachdb-on-premises) tutorial for guidance). To use GCE's TCP Proxy Load Balancing service: 1. For each zone in which you're running an instance, [create a distinct instance group](https://cloud.google.com/compute/docs/instance-groups/creating-groups-of-unmanaged-instances). * To ensure that the load balancer knows where to direct traffic, specify a port name mapping, with `tcp26257` as the **Port name** and `26257` as the **Port number**. 2. [Add the relevant instances to each instance group](https://cloud.google.com/compute/docs/instance-groups/creating-groups-of-unmanaged-instances#addinstances). 3. [Configure TCP Proxy Load Balancing](https://cloud.google.com/load-balancing/docs/tcp/setting-up-tcp#configure_load_balancer). * During backend configuration, create a health check, setting the **Protocol** to `HTTPS`, the **Port** to `8080`, and the **Request path** to path `/health?ready=1`. This [health endpoint](/docs/v26.4/monitoring-and-alerting) ensures that load balancers do not direct traffic to nodes that are live but not ready to receive requests. * If you want to maintain long-lived SQL connections that may be idle for more than tens of seconds, increase the backend timeout setting accordingly. * During frontend configuration, reserve a static IP address and note the IP address and the port you select. You'll use this address and port for all client connections. 4. [Create a firewall rule](https://cloud.google.com/load-balancing/docs/tcp/setting-up-tcp#config-hc-firewall) to allow traffic from the load balancer and health checker to your instances. This is necessary because TCP Proxy Load Balancing is implemented at the edge of the Google Cloud. * Be sure to set **Source IP ranges** to `130.211.0.0/22` and `35.191.0.0/16` and set **Target tags** to `cockroachdb` (not to the value specified in the linked instructions). ## Step 5. Generate certificates You can use `cockroach cert` commands or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to generate security certificates. This section features the `cockroach cert` commands. Locally, you'll need to [create the following certificates and keys](/docs/v26.4/cockroach-cert): * A certificate authority (CA) key pair (`ca.crt` and `ca.key`). * A node key pair for each node, issued to its IP addresses and any common names the machine uses, as well as to the IP addresses and common names for machines running load balancers. * A client key pair for the `root` user. You'll use this to run a sample workload against the cluster as well as some `cockroach` client commands from your local machine. 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac) on your local machine, if you haven't already. 2. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir my-safe-directory ``` * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes. * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. After that, you'll keep the key safe and secret; you will not upload it to your nodes. 3. Create the CA certificate and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Create the certificate and key for the first node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 5. Upload the CA certificate and node certificate and key to the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud compute ssh \ --project \ --command "mkdir certs" ``` > [!NOTE] > > `gcloud compute ssh` associates your public SSH key with the GCP project and is only needed when connecting to the first node. See the [GCP docs](https://cloud.google.com/sdk/gcloud/reference/compute/ssh) for more details. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ @@@@@ [!NOTE] > > This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key`. As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag. 1. Create the certificate and key for the second node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 2. Upload the CA certificate and node certificate and key to the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ssh @@@@@@ [!NOTE] > > On accessing the DB Console in a later step, your browser will consider the CockroachDB-created certificate invalid and you’ll need to click through a warning message to get to the UI. You can avoid this issue by [using a certificate issued by a public CA](/docs/v26.4/create-security-certificates-custom-ca#accessing-the-db-console-for-a-secure-cluster). ## Step 6. Start nodes > [!NOTE] > > By default, inter-node communication uses the internal IP addresses of your GCE instances. You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each initial node of your cluster, complete the following steps: > > > [!NOTE] > > > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. Visit [Releases](/docs/releases/index) and download the full binary of CockroachDB to the node. > > 2. On the node, follow the instructions to [install CockroachDB](/docs/v26.4/install-cockroachdb-mac). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > This command primes the node to start, using the following flags: > > | Flag | Description | > | - | - | > | `--certs-dir` | Specifies the directory where you placed the `ca.crt` file and the `node.crt` and `node.key` files for the node. | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > | `--cache` `--max-sql-memory` | Increases the node's cache size to 25% of available system memory to improve read performance. The capacity for in-memory SQL processing defaults to 25% of system memory but can be raised, if necessary, to increase the number of simultaneous client connections allowed by the node as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. For more details, see [Cache and SQL Memory Size](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). | > | `--background` | Starts the node in the background so you gain control of the terminal to issue more commands. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr= > Repeat these steps for each additional node that you want in your cluster. > [tab] systemd > > For each initial node of your cluster, complete the following steps: > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ chown -R cockroach /var/lib/cockroach > ``` > > 7. Save the following sample configuration template as `/etc/systemd/system/securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > 8. In the sample configuration template, specify values for the following flags: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=localhost:8080`. To set these options manually, see [Start a Node](/docs/v26.4/cockroach-start#standard-output). > > 9. Start the CockroachDB cluster: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl start securecockroachdb > ``` > > 10. Configure `systemd` to start CockroachDB automatically after a reboot: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl enable securecockroachdb > ``` > > 11. Repeat these steps for each additional node that you want in your cluster. > > > [!NOTE] > > > > `systemd` handles node restarts in case of node failure. To stop a node without `systemd` restarting it, run `systemctl stop securecockroachdb` ## Step 7. Initialize the cluster On your local machine, run the [`cockroach init`](/docs/v26.4/cockroach-init) command to complete the node startup process and have them join together as a cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --certs-dir=certs --host=
CREATE DATABASE securenodetest; ``` 3. View the cluster's databases, which will include `securenodetest`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW DATABASES; ``` ``` +--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | securenodetest | | pg_catalog | | system | +--------------------+ (5 rows) ``` 4. Use `\q` to exit the SQL shell. ## Step 9. Run a sample workload CockroachDB comes with a number of [built-in workloads](/docs/v26.4/cockroach-workload) for simulating client traffic. This step features CockroachDB's version of the [TPC-C](http://www.tpc.org/tpcc/) workload. > [!NOTE] > > Be sure that you have configured your network to allow traffic from the application to the load balancer. In this case, you will run the sample workload on one of your machines. The traffic source should therefore be the **internal (private)** IP address of that machine. 1. SSH to the machine where you want to run the sample TPC-C workload. This should be a machine that is not running a CockroachDB node, and it should already have a `certs` directory containing `ca.crt`, `client.root.crt`, and `client.root.key` files. 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). 3. Use the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to load the initial schema and data, pointing it at the IP address of the load balancer: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload init tpcc \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` 4. Use the `cockroach workload` command to run the workload for 10 minutes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload run tpcc \ --duration=10m \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` You'll see per-operation statistics print to standard output every second: ``` _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms) 1s 0 1443.4 1494.8 4.7 9.4 27.3 67.1 transfer 2s 0 1686.5 1590.9 4.7 8.1 15.2 28.3 transfer 3s 0 1735.7 1639.0 4.7 7.3 11.5 28.3 transfer 4s 0 1542.6 1614.9 5.0 8.9 12.1 21.0 transfer 5s 0 1695.9 1631.1 4.7 7.3 11.5 22.0 transfer 6s 0 1569.2 1620.8 5.0 8.4 11.5 15.7 transfer 7s 0 1614.6 1619.9 4.7 8.1 12.1 16.8 transfer 8s 0 1344.4 1585.6 5.8 10.0 15.2 31.5 transfer 9s 0 1351.9 1559.5 5.8 10.0 16.8 54.5 transfer 10s 0 1514.8 1555.0 5.2 8.1 12.1 16.8 transfer ... ``` After the specified duration (10 minutes in this case), the workload will stop and you'll see totals printed to standard output: ``` _elapsed___errors_____ops(total)___ops/sec(cum)__avg(ms)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)__result 600.0s 0 823902 1373.2 5.8 5.5 10.0 15.2 209.7 ``` > [!TIP] > > For more `tpcc` options, use `cockroach workload run tpcc --help`. For details about other workloads built into the `cockroach` binary, use `cockroach workload --help`. 1. To monitor the load generator's progress, open the [DB Console](/docs/v26.4/ui-overview) by pointing a browser to the address in the `admin` field in the standard output of any node on startup. Since the load generator is pointed at the load balancer, the connections will be evenly distributed across nodes. To verify this, click **Metrics** on the left, select the **SQL** dashboard, and then check the **SQL Connections** graph. You can use the **Graph** menu to filter the graph for specific nodes. ## Step 10. Monitor the cluster Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. For details about available monitoring options and the most important events and metrics to alert on, see [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting). ## Step 11. Scale the cluster You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command, passing the new node's address as the `--advertise-addr` flag and pointing `--join` to the three existing nodes (also include `--locality` if you set it earlier). > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > 4. Update your load balancer to recognize the new node. > [tab] systemd > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > chown -R cockroach /var/lib/cockroach > ``` > > 7. Copy the following sample configuration template into a file named `securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > Save the file in the `/etc/systemd/system/` directory. > > 8. Customize the sample configuration template for your deployment: > > Specify values for the following flags in the sample configuration template: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > 9. Repeat these steps for each additional node that you want in your cluster. ## Step 12. Use the database Now that your deployment is working, you can: 1. [Implement your data model](/docs/v26.4/sql-statements). 2. [Create users](/docs/v26.4/create-user) and [grant them privileges](/docs/v26.4/grant). 3. [Connect your application](/docs/v26.4/install-client-drivers). Be sure to connect your application to the load balancer, not to a CockroachDB node. 4. [Take backups](/docs/v26.4/take-full-and-incremental-backups) of your data. You may also want to adjust the way the cluster replicates data. For example, by default, a multi-node cluster replicates all data 3 times; you can change this replication factor or create additional rules for replicating individual databases and tables differently. For more information, see [Replication Controls](/docs/v26.4/configure-replication-zones). > [!CAUTION] > > When running a cluster of 5 nodes or more, it's safest to [increase the replication factor for important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) to 5, even if you do not do so for user data. For the cluster as a whole to remain available, the ranges for this internal data must always retain a majority of their replicas. ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Performance Tuning](/docs/v26.4/performance-best-practices-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Deploy CockroachDB on Microsoft Azure Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-on-microsoft-azure This page shows you how to manually deploy a secure multi-node CockroachDB cluster on Microsoft Azure, using Azure's managed load balancing service to distribute client traffic. If you are only testing CockroachDB, or you are not concerned with protecting network communication with TLS encryption, you can use an insecure cluster instead. Select **Insecure** above for instructions. > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. ## Before you begin ### Requirements * You must have [CockroachDB installed](/docs/v26.4/install-cockroachdb-mac) locally. This is necessary for generating and managing your deployment's certificates. * You must have [SSH access]() to each machine. This is necessary for distributing and starting CockroachDB binaries. * Your network configuration must allow TCP communication on the following ports: * `26257` for intra-cluster and client-cluster communication * `8080` to expose your DB Console * Carefully review the [Production Checklist](/docs/v26.4/recommended-production-settings), including supported hardware and software, and the recommended [Topology Patterns](/docs/v26.4/topology-patterns). * Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine. * To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see [Start a Node](/docs/v26.4/cockroach-start#store). If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`. * When starting each node, use the [`--locality`](/docs/v26.4/cockroach-start#locality) flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes. * When deploying in a single availability zone: * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the [`default` 3-way replication factor](/docs/v26.4/configure-replication-zones#view-the-default-replication-zone). In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority. * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and [increase the `default` replication factor for user data](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to 5. The replication factor for [important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority. * When deploying across multiple availability zones: * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas. * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption. * When deploying across multiple regions: * To be able to tolerate the failure of 1 entire region, use at least 3 regions. ### Recommendations * Decide how you want to access your DB Console: | Access Level | Description | | - | - | | Partially open | Set a firewall rule to allow only specific IP addresses to communicate on port `8080`. | | Completely open | Set a firewall rule to allow all IP addresses to communicate on port `8080`. | | Completely closed | Set a firewall rule to disallow all communication on port `8080`. In this case, a machine with SSH access to a node could use an SSH tunnel to access the DB Console. | ## Step 1. Configure your network CockroachDB requires TCP communication on two ports: * **26257** (`tcp:26257`) for inter-node communication (i.e., working as a cluster), for applications to connect to the load balancer, and for routing from the load balancer to nodes * **8080** (`tcp:8080`) for exposing your DB Console To enable this in Azure, you must create a Resource Group, Virtual Network, and Network Security Group. 1. [Create a Resource Group](https://azure.microsoft.com/updates/create-empty-resource-groups/). 2. [Create a Virtual Network](https://docs.microsoft.com/azure/virtual-network/virtual-networks-create-vnet-arm-pportal) that uses your **Resource Group**. 3. [Create a Network Security Group](https://docs.microsoft.com/azure/virtual-network/virtual-networks-create-nsg-arm-pportal) that uses your **Resource Group**, and then add the following **inbound** rules to it: * **DB Console support**: | Field | Recommended Value | | - | - | | Name | **cockroachadmin** | | Source | **IP Addresses** | | Source IP addresses/CIDR ranges | Your local network’s IP ranges | | Source port ranges | \* | | Destination | **Any** | | Destination port range | **8080** | | Protocol | **TCP** | | Action | **Allow** | | Priority | Any value > 1000 | * **Application support**: | Field | Recommended Value | | - | - | | Name | **cockroachapp** | | Source | **IP Addresses** | | Source IP addresses/CIDR ranges | Your local network’s IP ranges | | Source port ranges | \* | | Destination | **Any** | | Destination port range | **26257** | | Protocol | **TCP** | | Action | **Allow** | | Priority | Any value > 1000 | ## Step 2. Create VMs [Create Linux VMs](https://docs.microsoft.com/azure/virtual-machine-scale-sets/quick-create-portal) for each node you plan to have in your cluster. If you plan to run a sample workload against the cluster, create a separate VM for that workload. * Run at least 3 nodes to [ensure survivability](/docs/v26.4/recommended-production-settings#topology). * Use general-purpose [Dsv5-series](https://docs.microsoft.com/azure/virtual-machines/dv5-dsv5-series) and [Dasv5-series](https://docs.microsoft.com/azure/virtual-machines/dasv5-dadsv5-series) or memory-optimized [Ev5-series](https://docs.microsoft.com/azure/virtual-machines/ev5-esv5-series) and [Easv5-series](https://docs.microsoft.com/azure/virtual-machines/easv5-eadsv5-series#easv5-series) VMs. For example, Cockroach Labs has used `Standard_D8s_v5`, `Standard_D8as_v5`, `Standard_E8s_v5`, and `Standard_e8as_v5` for performance benchmarking. * Compute-optimized [F-series](https://docs.microsoft.com/azure/virtual-machines/fsv2-series) VMs are also acceptable. > [!CAUTION] > > Do not use ["burstable" B-series](https://docs.microsoft.com/azure/virtual-machines/linux/b-series-burstable) VMs, which limit the load on CPU resources. Also, Cockroach Labs has experienced data corruption issues on A-series VMs, so we recommend avoiding those as well. * When creating the VMs, make sure to select the **Resource Group**, **Virtual Network**, and **Network Security Group** you created. For more details, see [Hardware Recommendations](/docs/v26.4/recommended-production-settings#hardware) and [Cluster Topology](/docs/v26.4/recommended-production-settings#topology). ## Step 3. Synchronize clocks CockroachDB requires moderate levels of [clock synchronization](/docs/v26.4/recommended-production-settings#clock-synchronization) to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed (500ms by default), it spontaneously shuts down. This avoids the risk of consistency anomalies, but it's best to prevent clocks from drifting too far in the first place by running clock synchronization software on each node. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well. 1. SSH to the first machine. 2. Disable `timesyncd`, which tends to be active by default on some Linux distributions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo timedatectl set-ntp no ``` Verify that `timesyncd` is off: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ timedatectl ``` Look for `Network time on: no` or `NTP enabled: no` in the output. 3. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 4. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 5. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` > [!NOTE] > > We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 1. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 2. Repeat these steps for each machine where a CockroachDB node will run. Compute Engine instances are preconfigured to use [NTP](http://www.ntp.org/), which should keep offsets in the single-digit milliseconds. However, Google can’t predict how external NTP services, such as `pool.ntp.org`, will handle the leap second. Therefore, you should: * [Configure each GCE instance to use Google's internal NTP service](https://cloud.google.com/compute/docs/instances/configure-ntp#configure_ntp_for_your_instances). * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. Amazon provides the [Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html), which uses a fleet of satellite-connected and atomic reference clocks in each AWS Region to deliver accurate current time readings. The service also smears the leap second. * [Configure each AWS instance to use the internal Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure-amazon-time-service). * Per the above instructions, ensure that `etc/chrony.conf` on the instance contains the line `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` and that other `server` or `pool` lines are commented out. * To verify that Amazon Time Sync Service is being used, run `chronyc sources -v` and check for a line containing `* 169.254.169.123`. The `*` denotes the preferred time server. * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here. However, to run `ntpd` properly on Azure VMs, it's necessary to first unbind the Time Synchronization device used by the Hyper-V technology running Azure VMs; this device aims to synchronize time between the VM and its host operating system but has been known to cause problems. 1. SSH to the first machine. 2. Find the ID of the Hyper-V Time Synchronization device: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/lsvmbus ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python lsvmbus -vv | grep -w "Time Synchronization" -A 3 ``` ``` VMBUS ID 12: Class_ID = {9527e630-d0ae-497b-adce-e80ab0175caf} - [Time Synchronization] Device_ID = {2dd1ce17-079e-403c-b352-a1921ee207ee} Sysfs path: /sys/bus/vmbus/devices/2dd1ce17-079e-403c-b352-a1921ee207ee Rel_ID=12, target_cpu=0 ``` 3. Unbind the device, using the `Device_ID` from the previous command's output: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo | sudo tee /sys/bus/vmbus/drivers/hv_utils/unbind ``` 4. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 5. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 6. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 7. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 8. Repeat these steps for each machine where a CockroachDB node will run. ## Step 4. Set up load balancing Each CockroachDB node is an equally suitable SQL gateway to your cluster, but to ensure client performance and reliability, it's important to use load balancing: * **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second). * **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. In cases where a node fails, the load balancer redirects client traffic to available nodes. Microsoft Azure offers fully-managed load balancing to distribute traffic between instances. 1. [Add Azure load balancing](https://docs.microsoft.com/azure/load-balancer/load-balancer-overview). Be sure to: * Set forwarding rules to route TCP traffic from the load balancer's port **26257** to port **26257** on the nodes. * Configure health checks to use HTTP port **8080** and path `/health?ready=1`. This [health endpoint](/docs/v26.4/monitoring-and-alerting) ensures that load balancers do not direct traffic to nodes that are live but not ready to receive requests. 1. Note the provisioned **IP Address** for the load balancer. You'll use this later to test load balancing and to connect your application to the cluster. ## Step 5. Generate certificates You can use `cockroach cert` commands or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to generate security certificates. This section features the `cockroach cert` commands. Locally, you'll need to [create the following certificates and keys](/docs/v26.4/cockroach-cert): * A certificate authority (CA) key pair (`ca.crt` and `ca.key`). * A node key pair for each node, issued to its IP addresses and any common names the machine uses, as well as to the IP addresses and common names for machines running load balancers. * A client key pair for the `root` user. You'll use this to run a sample workload against the cluster as well as some `cockroach` client commands from your local machine. 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac) on your local machine, if you haven't already. 2. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir my-safe-directory ``` * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes. * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. After that, you'll keep the key safe and secret; you will not upload it to your nodes. 3. Create the CA certificate and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Create the certificate and key for the first node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 5. Upload the CA certificate and node certificate and key to the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud compute ssh \ --project \ --command "mkdir certs" ``` > [!NOTE] > > `gcloud compute ssh` associates your public SSH key with the GCP project and is only needed when connecting to the first node. See the [GCP docs](https://cloud.google.com/sdk/gcloud/reference/compute/ssh) for more details. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ @@@@@ [!NOTE] > > This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key`. As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag. 1. Create the certificate and key for the second node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 2. Upload the CA certificate and node certificate and key to the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ssh @@@@@@ [!NOTE] > > On accessing the DB Console in a later step, your browser will consider the CockroachDB-created certificate invalid and you’ll need to click through a warning message to get to the UI. You can avoid this issue by [using a certificate issued by a public CA](/docs/v26.4/create-security-certificates-custom-ca#accessing-the-db-console-for-a-secure-cluster). ## Step 6. Start nodes You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each initial node of your cluster, complete the following steps: > > > [!NOTE] > > > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. Visit [Releases](/docs/releases/index) and download the full binary of CockroachDB to the node. > > 2. On the node, follow the instructions to [install CockroachDB](/docs/v26.4/install-cockroachdb-mac). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > This command primes the node to start, using the following flags: > > | Flag | Description | > | - | - | > | `--certs-dir` | Specifies the directory where you placed the `ca.crt` file and the `node.crt` and `node.key` files for the node. | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > | `--cache` `--max-sql-memory` | Increases the node's cache size to 25% of available system memory to improve read performance. The capacity for in-memory SQL processing defaults to 25% of system memory but can be raised, if necessary, to increase the number of simultaneous client connections allowed by the node as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. For more details, see [Cache and SQL Memory Size](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). | > | `--background` | Starts the node in the background so you gain control of the terminal to issue more commands. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr= > Repeat these steps for each additional node that you want in your cluster. > [tab] systemd > > For each initial node of your cluster, complete the following steps: > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ chown -R cockroach /var/lib/cockroach > ``` > > 7. Save the following sample configuration template as `/etc/systemd/system/securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > 8. In the sample configuration template, specify values for the following flags: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=localhost:8080`. To set these options manually, see [Start a Node](/docs/v26.4/cockroach-start#standard-output). > > 9. Start the CockroachDB cluster: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl start securecockroachdb > ``` > > 10. Configure `systemd` to start CockroachDB automatically after a reboot: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl enable securecockroachdb > ``` > > 11. Repeat these steps for each additional node that you want in your cluster. > > > [!NOTE] > > > > `systemd` handles node restarts in case of node failure. To stop a node without `systemd` restarting it, run `systemctl stop securecockroachdb` ## Step 7. Initialize the cluster On your local machine, run the [`cockroach init`](/docs/v26.4/cockroach-init) command to complete the node startup process and have them join together as a cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --certs-dir=certs --host=
CREATE DATABASE securenodetest; ``` 3. View the cluster's databases, which will include `securenodetest`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW DATABASES; ``` ``` +--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | securenodetest | | pg_catalog | | system | +--------------------+ (5 rows) ``` 4. Use `\q` to exit the SQL shell. ## Step 9. Run a sample workload CockroachDB comes with a number of [built-in workloads](/docs/v26.4/cockroach-workload) for simulating client traffic. This step features CockroachDB's version of the [TPC-C](http://www.tpc.org/tpcc/) workload. > [!NOTE] > > Be sure that you have configured your network to allow traffic from the application to the load balancer. In this case, you will run the sample workload on one of your machines. The traffic source should therefore be the **internal (private)** IP address of that machine. 1. SSH to the machine where you want to run the sample TPC-C workload. This should be a machine that is not running a CockroachDB node, and it should already have a `certs` directory containing `ca.crt`, `client.root.crt`, and `client.root.key` files. 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). 3. Use the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to load the initial schema and data, pointing it at the IP address of the load balancer: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload init tpcc \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` 4. Use the `cockroach workload` command to run the workload for 10 minutes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload run tpcc \ --duration=10m \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` You'll see per-operation statistics print to standard output every second: ``` _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms) 1s 0 1443.4 1494.8 4.7 9.4 27.3 67.1 transfer 2s 0 1686.5 1590.9 4.7 8.1 15.2 28.3 transfer 3s 0 1735.7 1639.0 4.7 7.3 11.5 28.3 transfer 4s 0 1542.6 1614.9 5.0 8.9 12.1 21.0 transfer 5s 0 1695.9 1631.1 4.7 7.3 11.5 22.0 transfer 6s 0 1569.2 1620.8 5.0 8.4 11.5 15.7 transfer 7s 0 1614.6 1619.9 4.7 8.1 12.1 16.8 transfer 8s 0 1344.4 1585.6 5.8 10.0 15.2 31.5 transfer 9s 0 1351.9 1559.5 5.8 10.0 16.8 54.5 transfer 10s 0 1514.8 1555.0 5.2 8.1 12.1 16.8 transfer ... ``` After the specified duration (10 minutes in this case), the workload will stop and you'll see totals printed to standard output: ``` _elapsed___errors_____ops(total)___ops/sec(cum)__avg(ms)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)__result 600.0s 0 823902 1373.2 5.8 5.5 10.0 15.2 209.7 ``` > [!TIP] > > For more `tpcc` options, use `cockroach workload run tpcc --help`. For details about other workloads built into the `cockroach` binary, use `cockroach workload --help`. 1. To monitor the load generator's progress, open the [DB Console](/docs/v26.4/ui-overview) by pointing a browser to the address in the `admin` field in the standard output of any node on startup. Since the load generator is pointed at the load balancer, the connections will be evenly distributed across nodes. To verify this, click **Metrics** on the left, select the **SQL** dashboard, and then check the **SQL Connections** graph. You can use the **Graph** menu to filter the graph for specific nodes. ## Step 10. Monitor the cluster Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. For details about available monitoring options and the most important events and metrics to alert on, see [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting). ## Step 11. Scale the cluster You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command, passing the new node's address as the `--advertise-addr` flag and pointing `--join` to the three existing nodes (also include `--locality` if you set it earlier). > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > 4. Update your load balancer to recognize the new node. > [tab] systemd > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > chown -R cockroach /var/lib/cockroach > ``` > > 7. Copy the following sample configuration template into a file named `securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > Save the file in the `/etc/systemd/system/` directory. > > 8. Customize the sample configuration template for your deployment: > > Specify values for the following flags in the sample configuration template: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > 9. Repeat these steps for each additional node that you want in your cluster. ## Step 12. Use the database Now that your deployment is working, you can: 1. [Implement your data model](/docs/v26.4/sql-statements). 2. [Create users](/docs/v26.4/create-user) and [grant them privileges](/docs/v26.4/grant). 3. [Connect your application](/docs/v26.4/install-client-drivers). Be sure to connect your application to the load balancer, not to a CockroachDB node. 4. [Take backups](/docs/v26.4/take-full-and-incremental-backups) of your data. You may also want to adjust the way the cluster replicates data. For example, by default, a multi-node cluster replicates all data 3 times; you can change this replication factor or create additional rules for replicating individual databases and tables differently. For more information, see [Replication Controls](/docs/v26.4/configure-replication-zones). > [!CAUTION] > > When running a cluster of 5 nodes or more, it's safest to [increase the replication factor for important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) to 5, even if you do not do so for user data. For the cluster as a whole to remain available, the ranges for this internal data must always retain a majority of their replicas. ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Performance Tuning](/docs/v26.4/performance-best-practices-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Deploy CockroachDB On-Premises Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-on-premises This tutorial shows you how to manually deploy a secure multi-node CockroachDB cluster on multiple machines, using [HAProxy](http://www.haproxy.org/) load balancers to distribute client traffic. If you are only testing CockroachDB, or you are not concerned with protecting network communication with TLS encryption, you can use an insecure cluster instead. Select **Insecure** above for instructions. > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. ## Before you begin ### Requirements * You must have [CockroachDB installed](/docs/v26.4/install-cockroachdb-mac) locally. This is necessary for generating and managing your deployment's certificates. * You must have [SSH access]() to each machine. This is necessary for distributing and starting CockroachDB binaries. * Your network configuration must allow TCP communication on the following ports: * `26257` for intra-cluster and client-cluster communication * `8080` to expose your DB Console * Carefully review the [Production Checklist](/docs/v26.4/recommended-production-settings), including supported hardware and software, and the recommended [Topology Patterns](/docs/v26.4/topology-patterns). * Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine. * To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see [Start a Node](/docs/v26.4/cockroach-start#store). If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`. * When starting each node, use the [`--locality`](/docs/v26.4/cockroach-start#locality) flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes. * When deploying in a single availability zone: * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the [`default` 3-way replication factor](/docs/v26.4/configure-replication-zones#view-the-default-replication-zone). In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority. * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and [increase the `default` replication factor for user data](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to 5. The replication factor for [important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority. * When deploying across multiple availability zones: * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas. * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption. * When deploying across multiple regions: * To be able to tolerate the failure of 1 entire region, use at least 3 regions. ### Recommendations * Decide how you want to access your DB Console: | Access Level | Description | | - | - | | Partially open | Set a firewall rule to allow only specific IP addresses to communicate on port `8080`. | | Completely open | Set a firewall rule to allow all IP addresses to communicate on port `8080`. | | Completely closed | Set a firewall rule to disallow all communication on port `8080`. In this case, a machine with SSH access to a node could use an SSH tunnel to access the DB Console. | ## Step 1. Synchronize clocks CockroachDB requires moderate levels of [clock synchronization](/docs/v26.4/recommended-production-settings#clock-synchronization) to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed (500ms by default), it spontaneously shuts down. This avoids the risk of consistency anomalies, but it's best to prevent clocks from drifting too far in the first place by running clock synchronization software on each node. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here, but other methods of clock synchronization are suitable as well. 1. SSH to the first machine. 2. Disable `timesyncd`, which tends to be active by default on some Linux distributions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo timedatectl set-ntp no ``` Verify that `timesyncd` is off: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ timedatectl ``` Look for `Network time on: no` or `NTP enabled: no` in the output. 3. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 4. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 5. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` > [!NOTE] > > We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 1. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 2. Repeat these steps for each machine where a CockroachDB node will run. Compute Engine instances are preconfigured to use [NTP](http://www.ntp.org/), which should keep offsets in the single-digit milliseconds. However, Google can’t predict how external NTP services, such as `pool.ntp.org`, will handle the leap second. Therefore, you should: * [Configure each GCE instance to use Google's internal NTP service](https://cloud.google.com/compute/docs/instances/configure-ntp#configure_ntp_for_your_instances). * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. Amazon provides the [Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html), which uses a fleet of satellite-connected and atomic reference clocks in each AWS Region to deliver accurate current time readings. The service also smears the leap second. * [Configure each AWS instance to use the internal Amazon Time Sync Service](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure-amazon-time-service). * Per the above instructions, ensure that `etc/chrony.conf` on the instance contains the line `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` and that other `server` or `pool` lines are commented out. * To verify that Amazon Time Sync Service is being used, run `chronyc sources -v` and check for a line containing `* 169.254.169.123`. The `*` denotes the preferred time server. * If you plan to run a hybrid cluster across GCE and other cloud providers or environments, note that all of the nodes must be synced to the same time source, or to different sources that implement leap second smearing in the same way. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. [`ntpd`](http://doc.ntp.org/) should keep offsets in the single-digit milliseconds, so that software is featured here. However, to run `ntpd` properly on Azure VMs, it's necessary to first unbind the Time Synchronization device used by the Hyper-V technology running Azure VMs; this device aims to synchronize time between the VM and its host operating system but has been known to cause problems. 1. SSH to the first machine. 2. Find the ID of the Hyper-V Time Synchronization device: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/lsvmbus ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python lsvmbus -vv | grep -w "Time Synchronization" -A 3 ``` ``` VMBUS ID 12: Class_ID = {9527e630-d0ae-497b-adce-e80ab0175caf} - [Time Synchronization] Device_ID = {2dd1ce17-079e-403c-b352-a1921ee207ee} Sysfs path: /sys/bus/vmbus/devices/2dd1ce17-079e-403c-b352-a1921ee207ee Rel_ID=12, target_cpu=0 ``` 3. Unbind the device, using the `Device_ID` from the previous command's output: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ echo | sudo tee /sys/bus/vmbus/drivers/hv_utils/unbind ``` 4. Install the `ntp` package: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo apt-get install ntp ``` 5. Stop the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp stop ``` 6. Sync the machine's clock with Google's NTP service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpd -b time.google.com ``` To make this change permanent, in the `/etc/ntp.conf` file, remove or comment out any lines starting with `server` or `pool` and add the following lines: ``` server time1.google.com iburst server time2.google.com iburst server time3.google.com iburst server time4.google.com iburst ``` Restart the NTP daemon: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo service ntp start ``` We recommend Google's NTP service because it handles ["smearing" the leap second](https://developers.google.com/time/smear). If you use a different NTP service that doesn't smear the leap second, be sure to configure client-side smearing in the same way on each machine. See the [Production Checklist](/docs/v26.4/recommended-production-settings#considerations) for details. 7. Verify that the machine is using a Google NTP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ sudo ntpq -p ``` The active NTP server will be marked with an asterisk. 8. Repeat these steps for each machine where a CockroachDB node will run. ## Step 2. Generate certificates You can use `cockroach cert` commands or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to generate security certificates. This section features the `cockroach cert` commands. Locally, you'll need to [create the following certificates and keys](/docs/v26.4/cockroach-cert): * A certificate authority (CA) key pair (`ca.crt` and `ca.key`). * A node key pair for each node, issued to its IP addresses and any common names the machine uses, as well as to the IP addresses and common names for machines running load balancers. * A client key pair for the `root` user. You'll use this to run a sample workload against the cluster as well as some `cockroach` client commands from your local machine. 1. [Install CockroachDB](/docs/v26.4/install-cockroachdb-mac) on your local machine, if you haven't already. 2. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir my-safe-directory ``` * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes. * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. After that, you'll keep the key safe and secret; you will not upload it to your nodes. 3. Create the CA certificate and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Create the certificate and key for the first node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 5. Upload the CA certificate and node certificate and key to the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud compute ssh \ --project \ --command "mkdir certs" ``` > [!NOTE] > > `gcloud compute ssh` associates your public SSH key with the GCP project and is only needed when connecting to the first node. See the [GCP docs](https://cloud.google.com/sdk/gcloud/reference/compute/ssh) for more details. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ scp certs/ca.crt \ certs/node.crt \ certs/node.key \ @@@@@ [!NOTE] > > This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key`. As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag. 1. Create the certificate and key for the second node, issued to all common names you might use to refer to the node as well as to the load balancer instances: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ \ \ \ \ localhost \ 127.0.0.1 \ \ \ \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 2. Upload the CA certificate and node certificate and key to the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ssh @@@@@@ [!NOTE] > > On accessing the DB Console in a later step, your browser will consider the CockroachDB-created certificate invalid and you’ll need to click through a warning message to get to the UI. You can avoid this issue by [using a certificate issued by a public CA](/docs/v26.4/create-security-certificates-custom-ca#accessing-the-db-console-for-a-secure-cluster). ## Step 3. Start nodes You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each initial node of your cluster, complete the following steps: > > > [!NOTE] > > > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. Visit [Releases](/docs/releases/index) and download the full binary of CockroachDB to the node. > > 2. On the node, follow the instructions to [install CockroachDB](/docs/v26.4/install-cockroachdb-mac). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > This command primes the node to start, using the following flags: > > | Flag | Description | > | - | - | > | `--certs-dir` | Specifies the directory where you placed the `ca.crt` file and the `node.crt` and `node.key` files for the node. | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > | `--cache` `--max-sql-memory` | Increases the node's cache size to 25% of available system memory to improve read performance. The capacity for in-memory SQL processing defaults to 25% of system memory but can be raised, if necessary, to increase the number of simultaneous client connections allowed by the node as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. For more details, see [Cache and SQL Memory Size](/docs/v26.4/recommended-production-settings#cache-and-sql-memory-size). | > | `--background` | Starts the node in the background so you gain control of the terminal to issue more commands. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr= > Repeat these steps for each additional node that you want in your cluster. > [tab] systemd > > For each initial node of your cluster, complete the following steps: > > After completing these steps, nodes will not yet be live. They will complete the startup process and join together to form a cluster as soon as the cluster is initialized in the next step. > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ chown -R cockroach /var/lib/cockroach > ``` > > 7. Save the following sample configuration template as `/etc/systemd/system/securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > 8. In the sample configuration template, specify values for the following flags: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > When deploying across multiple datacenters, or when there is otherwise high latency between nodes, it is recommended to set `--locality` as well. For more details, see [Locality](/docs/v26.4/cockroach-start#locality). > > For other flags not explicitly set, the command uses default values. For example, the node stores data in `--store=cockroach-data` and binds DB Console HTTP requests to `--http-addr=localhost:8080`. To set these options manually, see [Start a Node](/docs/v26.4/cockroach-start#standard-output). > > 9. Start the CockroachDB cluster: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl start securecockroachdb > ``` > > 10. Configure `systemd` to start CockroachDB automatically after a reboot: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > systemctl enable securecockroachdb > ``` > > 11. Repeat these steps for each additional node that you want in your cluster. > > > [!NOTE] > > > > `systemd` handles node restarts in case of node failure. To stop a node without `systemd` restarting it, run `systemctl stop securecockroachdb` ## Step 4. Initialize the cluster On your local machine, run the [`cockroach init`](/docs/v26.4/cockroach-init) command to complete the node startup process and have them join together as a cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach init --certs-dir=certs --host=
CREATE DATABASE securenodetest; ``` 3. View the cluster's databases, which will include `securenodetest`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SHOW DATABASES; ``` ``` +--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | securenodetest | | pg_catalog | | system | +--------------------+ (5 rows) ``` 4. Use `\q` to exit the SQL shell. ## Step 6. Set up load balancing Each CockroachDB node is an equally suitable SQL gateway to your cluster, but to ensure client performance and reliability, it's important to use load balancing: * **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second). * **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. In cases where a node fails, the load balancer redirects client traffic to available nodes. [HAProxy](http://www.haproxy.org/) is one of the most popular open-source TCP load balancers, and CockroachDB includes a built-in command for generating a configuration file that is preset to work with your running cluster, so we feature that tool here. 1. On your local machine, run the [`cockroach gen haproxy`](/docs/v26.4/cockroach-gen) command with the `--host` flag set to the address of any node and security flags pointing to the CA cert and the client cert and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach gen haproxy \ --certs-dir=certs \ --host=
:26257 check port 8080 server cockroach2 :26257 check port 8080 server cockroach3 :26257 check port 8080 ``` The file is preset with the minimal [configurations](http://cbonte.github.io/haproxy-dconv/1.7/configuration.html) needed to work with your running cluster: | Field | Description | | - | - | | `timeout connect` `timeout client` `timeout server` | Timeout values that should be suitable for most deployments. | | `bind` | The port that HAProxy listens on. This is the port clients will connect to and thus needs to be allowed by your network configuration. This tutorial assumes HAProxy is running on a separate machine from CockroachDB nodes. If you run HAProxy on the same machine as a node (not recommended), you'll need to change this port, as `26257` is likely already being used by the CockroachDB node. | | `balance` | The balancing algorithm. This is set to `roundrobin` to ensure that connections get rotated amongst nodes (connection 1 on node 1, connection 2 on node 2, etc.). Check the [HAProxy Configuration Manual](http://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4-balance) for details about this and other balancing algorithms. | | `option httpchk` | The HTTP endpoint that HAProxy uses to check node health. [`/health?ready=1`](/docs/v26.4/monitoring-and-alerting) ensures that HAProxy doesn't direct traffic to nodes that are live but not ready to receive requests. | | `server` | For each included node, this field specifies the address the node advertises to other nodes in the cluster, i.e., the addressed pass in the [`--advertise-addr` flag](/docs/v26.4/cockroach-start#networking) on node startup. Make sure hostnames are resolvable and IP addresses are routable from HAProxy. | > [!NOTE] > > For full details on these and other configuration settings, see the [HAProxy Configuration Manual](http://cbonte.github.io/haproxy-dconv/1.7/configuration.html). 1. Upload the `haproxy.cfg` file to the machine where you want to run HAProxy: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} scp haproxy.cfg @ [!NOTE] > > Be sure that you have configured your network to allow traffic from the application to the load balancer. In this case, you will run the sample workload on one of your machines. The traffic source should therefore be the **internal (private)** IP address of that machine. 1. SSH to the machine where you want to run the sample TPC-C workload. This should be a machine that is not running a CockroachDB node, and it should already have a `certs` directory containing `ca.crt`, `client.root.crt`, and `client.root.key` files. 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). 3. Use the [`cockroach workload`](/docs/v26.4/cockroach-workload) command to load the initial schema and data, pointing it at the IP address of the load balancer: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload init tpcc \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` 4. Use the `cockroach workload` command to run the workload for 10 minutes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach workload run tpcc \ --duration=10m \ 'postgresql://root@:26257/tpcc?sslmode=verify-full&sslrootcert=certs/ca.crt&sslcert=certs/client.root.crt&sslkey=certs/client.root.key' ``` You'll see per-operation statistics print to standard output every second: ``` _elapsed___errors__ops/sec(inst)___ops/sec(cum)__p50(ms)__p95(ms)__p99(ms)_pMax(ms) 1s 0 1443.4 1494.8 4.7 9.4 27.3 67.1 transfer 2s 0 1686.5 1590.9 4.7 8.1 15.2 28.3 transfer 3s 0 1735.7 1639.0 4.7 7.3 11.5 28.3 transfer 4s 0 1542.6 1614.9 5.0 8.9 12.1 21.0 transfer 5s 0 1695.9 1631.1 4.7 7.3 11.5 22.0 transfer 6s 0 1569.2 1620.8 5.0 8.4 11.5 15.7 transfer 7s 0 1614.6 1619.9 4.7 8.1 12.1 16.8 transfer 8s 0 1344.4 1585.6 5.8 10.0 15.2 31.5 transfer 9s 0 1351.9 1559.5 5.8 10.0 16.8 54.5 transfer 10s 0 1514.8 1555.0 5.2 8.1 12.1 16.8 transfer ... ``` After the specified duration (10 minutes in this case), the workload will stop and you'll see totals printed to standard output: ``` _elapsed___errors_____ops(total)___ops/sec(cum)__avg(ms)__p50(ms)__p95(ms)__p99(ms)_pMax(ms)__result 600.0s 0 823902 1373.2 5.8 5.5 10.0 15.2 209.7 ``` > [!TIP] > > For more `tpcc` options, use `cockroach workload run tpcc --help`. For details about other workloads built into the `cockroach` binary, use `cockroach workload --help`. 1. To monitor the load generator's progress, open the [DB Console](/docs/v26.4/ui-overview) by pointing a browser to the address in the `admin` field in the standard output of any node on startup. Since the load generator is pointed at the load balancer, the connections will be evenly distributed across nodes. To verify this, click **Metrics** on the left, select the **SQL** dashboard, and then check the **SQL Connections** graph. You can use the **Graph** menu to filter the graph for specific nodes. ## Step 8. Monitor the cluster Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. For details about available monitoring options and the most important events and metrics to alert on, see [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting). ## Step 9. Scale the cluster You can start the nodes manually or automate the process using [systemd](https://www.freedesktop.org/wiki/Software/systemd/). > [tab] Manual > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Run the [`cockroach start`](/docs/v26.4/cockroach-start#standard-output) command, passing the new node's address as the `--advertise-addr` flag and pointing `--join` to the three existing nodes (also include `--locality` if you set it earlier). > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach start \ > --certs-dir=certs \ > --advertise-addr= --join= --cache=.25 \ > --max-sql-memory=.25 \ > --background > ``` > > 4. Update your load balancer to recognize the new node. > [tab] systemd > > For each additional node you want to add to the cluster, complete the following steps: > > 1. SSH to the machine where you want the node to run. Ensure you are logged in as the `root` user. > > 2. [Install CockroachDB for Linux](/docs/v26.4/install-cockroachdb-linux). > > 3. Create the Cockroach directory: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mkdir /var/lib/cockroach > ``` > > 4. Create a Unix user named `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > useradd cockroach > ``` > > 5. Move the `certs` directory to the `cockroach` directory. > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > mv certs /var/lib/cockroach/ > ``` > > 6. Change the ownership of the `cockroach` directory to the user `cockroach`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > chown -R cockroach /var/lib/cockroach > ``` > > 7. Copy the following sample configuration template into a file named `securecockroachdb.service`: > > ```ini theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > [Unit] > Description=Cockroach Database cluster node > Requires=network.target > [Service] > Type=notify > WorkingDirectory=/var/lib/cockroach > ExecStart=/usr/local/bin/cockroach start --certs-dir=certs --advertise-addr= --join=,, --cache=.25 --max-sql-memory=.25 > TimeoutStopSec=300 > Restart=always > RestartSec=10 > StandardOutput=syslog > StandardError=syslog > SyslogIdentifier=cockroach > User=cockroach > [Install] > WantedBy=default.target > ``` > > Save the file in the `/etc/systemd/system/` directory. > > 8. Customize the sample configuration template for your deployment: > > Specify values for the following flags in the sample configuration template: > > | Flag | Description | > | - | - | > | `--advertise-addr` | Specifies the IP address/hostname and port to tell other nodes to use. The port number can be omitted, in which case it defaults to `26257`. This value must route to an IP address the node is listening on (with `--listen-addr` unspecified, the node listens on all IP addresses). In some networking scenarios, you may need to use `--advertise-addr` and/or `--listen-addr` differently. For more details, see [Networking](/docs/v26.4/recommended-production-settings#networking). | > | `--join` | Identifies the address of 3-5 of the initial nodes of the cluster. These addresses should match the addresses that the target nodes are advertising. | > > 9. Repeat these steps for each additional node that you want in your cluster. ## Step 10. Use the cluster Now that your deployment is working, you can: 1. [Implement your data model](/docs/v26.4/sql-statements). 2. [Create users](/docs/v26.4/create-user) and [grant them privileges](/docs/v26.4/grant). 3. [Connect your application](/docs/v26.4/install-client-drivers). Be sure to connect your application to the load balancer, not to a CockroachDB node. 4. [Take backups](/docs/v26.4/take-full-and-incremental-backups) of your data. You may also want to adjust the way the cluster replicates data. For example, by default, a multi-node cluster replicates all data 3 times; you can change this replication factor or create additional rules for replicating individual databases and tables differently. For more information, see [Replication Controls](/docs/v26.4/configure-replication-zones). > [!CAUTION] > > When running a cluster of 5 nodes or more, it's safest to [increase the replication factor for important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) to 5, even if you do not do so for user data. For the cluster as a whole to remain available, the ranges for this internal data must always retain a majority of their replicas. ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Performance Tuning](/docs/v26.4/performance-best-practices-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Deploy CockroachDB with the CockroachDB Operator Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-with-cockroachdb-operator This page describes how to start and stop a secure 3-node CockroachDB cluster in a single [Kubernetes](http://kubernetes.io/) cluster. ## Prerequisites and best practices ### Kubernetes version To deploy CockroachDB v25.1 or later, Kubernetes 1.30 or higher is required. Cockroach Labs strongly recommends that you use a Kubernetes version that is eligible for [patch support by the Kubernetes project](https://kubernetes.io/releases/). ### Helm version The CockroachDB Helm chart requires Helm 3.0 or higher. If you attempt to use an incompatible Helm version, an error like the following occurs: ``` Error: UPGRADE FAILED: template: cockroachdb/templates/tests/client.yaml:6:14: executing "cockroachdb/templates/tests/client.yaml" at <.Values.networkPolicy.enabled>: nil pointer evaluating interface {}.enabled ``` There are two Helm charts that must be deployed: * `operator`: The CockroachDB operator chart to be installed first. * `cockroachdb`: The CockroachDB application chart to be installed after the operator is ready. ### Network Service Name Indication (SNI) is an extension to the TLS protocol that allows a client to indicate which hostname it is attempting to connect to at the start of the TCP handshake process. The server can present multiple certificates on the same IP address and TCP port number, and one server can serve multiple secure websites or API services even if they use different certificates. Due to its order of operations, the PostgreSQL wire protocol's implementation of TLS is incompatible with SNI-based routing in the Kubernetes ingress controller. Instead, use a TCP load balancer for CockroachDB that is not shared with other services. If you want to secure your cluster to use TLS certificates for all network communications, Helm must be installed with RBAC privileges. Otherwise, you will get an `attempt to grant extra privileges` error. ### Localities CockroachDB clusters use localities to efficiently distribute replicas. This is especially important for [multi-region deployments](#multi-region-deployments). With the CockroachDB operator, you specify mappings between locality levels and the location on a Kubernetes node where the value for that locality can be found. In cloud provider deployments (e.g., [GKE](#hosted-gke), [EKS](#hosted-eks), or [AKS](#hosted-aks)), the [`topology.kubernetes.io/region`](https://kubernetes.io/docs/reference/labels-annotations-taints/#topologykubernetesioregion) and [`topology.kubernetes.io/zone`](https://kubernetes.io/docs/reference/labels-annotations-taints/#topologykubernetesiozone) values on Kubernetes nodes are populated by cloud provider. For further granularity, you can define arbitrary locality labels (e.g., `province`, `datacenter`, `rack`), but these need to be applied individually to the Kubernetes node when initialized so that CockroachDB can understand where the node lives and distribute replicas accordingly. On bare metal Kubernetes deployments, you must plan a hierarchy of localities that suit your CockroachDB node distribution, then apply these values individually to nodes when they are initialized. Although you can set most of these values arbitrarily, you must set region and zone locations in the reserved `topology.kubernetes.io/region` and `topology.kubernetes.io/zone` namespaces, respectively. For more information on how locality labels are used by CockroachDB, refer to the [`--locality` documentation](/docs/v26.4/cockroach-start#locality). ### Architecture The CockroachDB operator is only supported in environments with an ARM64 or AMD64 architecture. ### Resources When starting Kubernetes, select machines with at least 4 vCPUs and 16 GiB of memory, and provision at least 2 vCPUs and 8 GiB of memory to CockroachDB per pod. These minimum settings are used by default in this deployment guide, and are appropriate for testing purposes only. On a production deployment, you should adjust the resource settings for your workload. ### Storage Kubernetes deployments use external persistent volumes that are often replicated by the provider. CockroachDB replicates data automatically, and this redundant layer of [replication](/docs/v26.4/architecture/overview#replication) can impact performance. Using [local volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local) may improve performance. ### Multi-region deployments The following deployment requirements and best practices apply to multi-region deployments with the CockroachDB operator: * Plan an operator deployment in each region. Each operator handles CockroachDB node management in its own region, so you must factor that there are multiple operator deployments into your upgrade and maintenance strategy to ensure availability. * VPC peering and CoreDNS are needed to resolve services and discovery across regions. Refer to the documentation for your cloud solution to configure your cross-region network accordingly. * Make sure that region is part of your [locality](#localities) configuration and nodes are tagged consistently with their deployment region. For deployments with a cloud service provider this is handled automatically, but must be applied manually for bare metal deployments. * A single certificate authority (CA) across all regions is required. One namespace per region is recommended to simplify certificate management. ## Step 1. Start Kubernetes You can use the hosted [Google Kubernetes Engine (GKE)](#hosted-gke) service, hosted [Amazon Elastic Kubernetes Service (EKS)](#hosted-eks), or [Microsoft Azure Kubernetes Service (AKS)](#hosted-aks) to quickly start Kubernetes. > [!TIP] > > Cloud providers such as GKE, EKS, and AKS are not required to run CockroachDB on Kubernetes. You can use any cluster hardware with the minimum recommended Kubernetes version and at least 3 pods, each presenting sufficient resources to start a CockroachDB node. However, note that support for other deployments may vary. > > You can also evaluate a CockroachDB Kubernetes deployment on a local machine with [minikube](https://minikube.sigs.k8s.io/docs/start/). ### Hosted GKE 1. Complete the **Before You Begin** steps described in the [Google Kubernetes Engine Quickstart](https://cloud.google.com/kubernetes-engine/docs/quickstart) documentation. This includes installing `gcloud`, which is used to create and delete Kubernetes Engine clusters, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. The documentation offers the choice of using Google's Cloud Shell product or using a local shell on your machine. Choose to use a local shell if you want to be able to view the DB Console using the steps in this guide. 2. From your local workstation, start the Kubernetes cluster, specifying one of the available [regions](https://cloud.google.com/compute/docs/regions-zones#available) (e.g., `us-east1`). The process can take a few minutes, so do not move on to the next step until you see a `Creating cluster cockroachdb...done` message and details about your cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud container clusters create cockroachdb --machine-type n2-standard-4 --region {region-name} --num-nodes 1 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Creating cluster cockroachdb...done. ``` > [!NOTE] > > Since this region can differ from your default `gcloud` region, be sure to include the `--region` flag to run `gcloud` commands against this cluster. > This creates GKE instances and joins them into a single Kubernetes cluster named `cockroachdb`. The `--region` flag specifies a [regional three-zone cluster](https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-regional-cluster), and `--num-nodes` specifies one Kubernetes worker node in each zone. The `--machine-type` flag tells the node pool to use the [n2-standard-4](https://cloud.google.com/compute/docs/machine-types#standard_machine_types) machine type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). > [!NOTE] > > Consider creating another, dedicated node group for the operator pod for system resource availability. 1. Get the email address associated with your Google Cloud account: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud info | grep Account ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Account: [your.google.cloud.email@example.org] ``` The preceding command returns your email address in all lowercase. However, in the next step, you must enter the address using the accurate capitalization. For example, if your address is `YourName@example.com`, you must use `YourName@example.com` and not `yourname@example.com`. 2. [Create the RBAC roles](https://cloud.google.com/kubernetes-engine/docs/how-to/role-based-access-control#prerequisites_for_using_role-based_access_control) CockroachDB needs for running on GKE, using the address from the previous step: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create clusterrolebinding $USER-cluster-admin-binding \ --clusterrole=cluster-admin \ --user={your.google.cloud.email@example.org} ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} clusterrolebinding.rbac.authorization.k8s.io/your.username-cluster-admin-binding created ``` ### Hosted EKS 1. Complete the steps described in the [EKS Getting Started](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) documentation. This includes installing and configuring the AWS CLI and `eksctl`, which is the command-line tool used to create and delete Kubernetes clusters on EKS, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. If you are running [EKS-Anywhere](https://aws.amazon.com/eks/eks-anywhere/), CockroachDB requires that you [configure your default storage class](https://kubernetes.io/docs/tasks/administer-cluster/change-default-storage-class/) to auto-provision persistent volumes. Alternatively, you can define a custom storage configuration as required by your install pattern. 2. From your local workstation, start the Kubernetes cluster: To ensure that all 3 nodes can be placed into a different availability zone, you may want to first [confirm that at least 3 zones are available in the region](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#availability-zones-describe) for your account. Cluster provisioning usually takes between 10 and 15 minutes. Do not move on to the next step until you see a message like `[✔] EKS cluster "cockroachdb" in "us-east-1" region is ready` and details about your cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} eksctl create cluster \ --name cockroachdb \ --nodegroup-name standard-workers \ --node-type m6i.xlarge \ --nodes 3 \ --nodes-min 1 \ --nodes-max 4 \ --node-ami auto ``` This creates EKS instances and joins them into a single Kubernetes cluster named `cockroachdb`. The `--node-type` flag tells the node pool to use the [m6i.xlarge](https://aws.amazon.com/ec2/instance-types/) instance type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). Consider creating another, dedicated node group for the operator pod for system resource availability. 3. Open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) to verify that the stacks `eksctl-cockroachdb-cluster` and `eksctl-cockroachdb-nodegroup-standard-workers` were successfully created. Be sure that your region is selected in the console. ### Hosted AKS 1. Complete the **Before you begin**, **Define environment variables**, and **Create a resource groups** steps described in the [AKS quickstart guide](https://learn.microsoft.com/azure/aks/learn/quick-kubernetes-deploy-cli). This includes setting up the Azure CLI and the `az` tool, which is the command-line tool to create and manage Azure cloud resources. Set the environment variables as desired for your CockroachDB deployment. For these instructions, set the `MY_AKS_CLUSTER_NAME` variable to `cockroachdb`. Do not follow the **Create an AKS cluster** steps or following sections of the AKS quickstart guide, as these topics will be described specifically for CockroachDB in this documentation. 2. From your workstation, create the Kubernetes cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} az aks create \ --resource-group $MY_RESOURCE_GROUP_NAME \ --name $MY_AKS_CLUSTER_NAME \ --node-count 3 \ --generate-ssh-keys ``` 3. Configure authentication for the CockroachbDB operator. The operator can use [Azure Managed Identities](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview) if they are configured. If Azure Managed Identities are not configured for the CockroachDB operator, create an application in your Azure tenant and create a secret named `azure-cluster-identity-credentials-secret` that contains `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` to hold the application credentials. You can use the following example YAML to define this application: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: v1 kind: Secret metadata: name: azure-cluster-identity-credentials-secret type: Opaque stringData: azure-credentials: | azure_tenant_id: {tenant ID} azure_client_id: {client ID} azure_client_secret: {client secret} ``` For more information on how to use these variables, refer to the [`Azure.Identity` documentation](https://learn.microsoft.com/dotnet/api/azure.identity.environmentcredential?view=azure-dotnet). ### OpenShift deployments To deploy to an OpenShift cluster, the OpenShift Container Platform must be version 4.17 or later. ### Bare metal deployments For bare metal deployments, the specific Kubernetes infrastructure deployment steps should be similar to those described in [Hosted GKE](#hosted-gke) and [Hosted EKS](#hosted-eks). * You must plan a hierarchy of [locality labels](#localities) that suit your CockroachDB node distribution, then apply these labels individually to nodes when they are initialized. Although you can set most of these values arbitrarily, you must set region and zone locations in the reserved `topology.kubernetes.io/region` and `topology.kubernetes.io/zone` namespaces, respectively. ## Step 2. Start CockroachDB ### Add the CockroachDB Helm repository 1. Add the CockroachDB Helm repository: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm repo add cockroachdb-v2 https://charts.cockroachdb.com/v2 --force-update helm repo update cockroachdb-v2 # List available operator chart versions. helm search repo cockroachdb-v2/cockroachdb-operator-chart --versions # List available CockroachDB chart versions and pick the desired patch. # To include release candidate versions of CockroachDB, append the --devel flag to 'helm search'. helm search repo cockroachdb-v2/cockroachdb-chart --versions ``` Learn more about CockroachDB Helm chart versioning in the [Helm charts repository](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-operator/docs/VERSIONING.md). The operator's source code is available in the [cockroachdb/cockroachdb-operator](https://github.com/cockroachdb/cockroachdb-operator) repository. CockroachDB production charts are also published as OCI artifacts if preferred: **Google Artifact Registry**: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm pull oci://us-docker.pkg.dev/releases-prod/self-hosted/charts/cockroachdb-operator-chart --version 1.0.0 # Google Artifact Registry carries the same chart versions as the Helm repository. # Run the following command to list the available {CHART_VERSION} numbers: helm search repo cockroachdb-v2/cockroachdb-chart --versions helm pull oci://us-docker.pkg.dev/releases-prod/self-hosted/charts/cockroachdb-chart --version {CHART_VERSION} ``` **DockerHub**: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm pull oci://registry-1.docker.io/cockroachdb/cockroachdb-operator-chart --version 1.0.0 # DockerHub carries the same chart versions as the Helm repository. # Run the following command to list the available {CHART_VERSION} numbers: helm search repo cockroachdb-v2/cockroachdb-chart --versions helm pull oci://registry-1.docker.io/cockroachdb/cockroachdb-chart --version {CHART_VERSION} ``` The DockerHub repositories must exist before pulling charts unless DockerHub auto-create is enabled. 2. Set your environment variables. This step is optional but recommended in order to use the example commands and templates described in the following instructions. Note the default Kubernetes namespace of `cockroach-ns`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export CRDBOPERATOR=crdb-operator export CRDBCLUSTER=cockroachdb export NAMESPACE=cockroach-ns ``` 3. Install the operator sub-chart: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create namespace $NAMESPACE ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm install $CRDBOPERATOR cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 -n $NAMESPACE ``` ### Initialize the cluster 1. Generate a values file that tells Helm how to configure the Kubernetes cluster with the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm show values cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} > values.yaml ``` 2. Open `values.yaml` in a text editor. 3. Modify the `cockroachdb.crdbCluster.regions` section to describe the number of CockroachDB nodes to deploy and what region(s) to deploy them in. Replace the default `cloudProvider` with the appropriate value (`gcp`, `aws`, `azure`). For bare metal deployments, you can remove the `cloudProvider` field. The following example initializes three nodes on Google Cloud in the `us-central1` region: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: regions: - code: us-central1 nodes: 3 cloudProvider: gcp namespace: cockroach-ns ``` > [!NOTE] > > If you intend to deploy CockroachDB nodes across multiple different regions, follow the additional steps described in [Deploy across multiple regions](#deploy-across-multiple-regions). > > 1. Modify `cockroachdb.crdbCluster.podTemplate.spec.resources` in the values file with the CPU and memory limits and requests for each node to use. For example, to define default values of 4vCPU and 16GiB of memory: > > ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > cockroachdb: > crdbCluster: > podTemplate: > spec: > resources: > limits: > cpu: 4000m > memory: 16Gi > requests: > cpu: 4000m > memory: 16gi > ``` > > For more information on configuring node resource allocation, refer to [Resource management](/docs/v26.4/configure-cockroachdb-operator) > > 2. Modify the TLS configuration as desired. For a secure deployment, set `cockroachdb.tls.enabled` in the values file to `true`. By default, the certificates are created automatically by a self-signer utility, which requires no configuration beyond setting a custom certificate duration if desired. This utility uses `cockroach cert` to automatically generate self-signed certificates for the nodes and root client which are stored in a secret. You can see these certificates by running `kubectl get secrets`: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > kubectl get secrets > ``` > > ``` > crdb-cockroachdb-ca-secret Opaque 2 23s > crdb-cockroachdb-client-secret kubernetes.io/tls 3 22s > crdb-cockroachdb-node-secret kubernetes.io/tls 3 23s > ``` > > If you are deploying on OpenShift you must also set `cockroachdb.tls.selfSigner.securityContext.enabled` to `false` to mitigate stricter security policies. > If your organization's security policy requires that you use a custom CA certificate or otherwise use your own certificates, read the [certificate management documentation](/docs/v26.4/secure-cockroachdb-operator#tls-configuration-options). 1. In `cockroachdb.crdbCluster.localityMappings`, provide [locality mappings](#localities) that define locality levels and map them to node labels where the locality information of each Kubernetes node is stored. When CockroachDB is initialized on a node, it processes these values as though they are provided through the [`cockroach start --locality`](/docs/v26.4/cockroach-start#locality) flag. If `localityMappings` is not configured, by default the CockroachDB operator uses the `region` and `zone` locality labels, mapped implicitly to the [`topology.kubernetes.io/region`](https://kubernetes.io/docs/reference/labels-annotations-taints/#topologykubernetesioregion) and [`topology.kubernetes.io/zone`](https://kubernetes.io/docs/reference/labels-annotations-taints/#topologykubernetesiozone) node labels. * In cloud provider deployments, the `topology.kubernetes.io/region` and `topology.kubernetes.io/zone` values on a node are populated by the cloud provider. * In bare metal deployments, the `topology.kubernetes.io/region` and `topology.kubernetes.io/zone` node label values are not set implicitly by a cloud provider when initializing the node, so you must set them manually or configure custom locality labels. To add more granular levels of locality to your nodes or use different locality labels, add custom locality levels as values in the `cockroachdb.crdbCluster.localityMappings` list. Any custom `localityMappings` configuration overrides the default `region` and `zone` configuration, so if you append an additional locality level but wish to keep the `region` and `zone` labels you must declare them manually. The following example uses the existing `region` and `zone` labels and adds an additional `datacenter` locality mapping that is more granular than `zone`. This example declares that the `dc` locality information is stored in the `example.datacenter.locality` node label: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: localityMappings: - nodeLabel: "topology.kubernetes.io/region" localityLabel: "region" - nodeLabel: "topology.kubernetes.io/zone" localityLabel: "zone" - nodeLabel: "example.datacenter.locality" localityLabel: "dc" ``` The list of `localityMappings` is processed in a top-down hierarchy, where each entry is processed as a lower locality level than the previous locality. In this example, if a Kubernetes node is initialized in the `us-central1` region, `us-central1-c` zone, and `dc2` datacenter, its `cockroach start --locality` flag would be equivalent to the following: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach start --locality region=us-central1,zone=us-central1-c,dc=dc2 ``` Optionally, review the `cockroachdb.crdbCluster.podTemplate.spec.topologySpreadConstraints` configuration and set `topologyKey` to the `nodeLabel` value of a locality level that has distinct values for each node. By default the lowest locality level is `zone`, so the following configuration sets that value as the `topologyKey`: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: podTemplate: spec: topologySpreadConstraints: # maxSkew defines the degree to which the pods can be unevenly distributed. - maxSkew: 1 # topologyKey defines the key for topology spread. topologyKey: topology.kubernetes.io/zone ``` For more information on localities and topology planning, see the [topology patterns documentation](/docs/v26.4/topology-patterns). 2. Modify other relevant parts of the configuration such as other `topologySpreadConstraints` fields, `service.ports`, and others as needed for your configuration. 3. Run the following command to install the CockroachDB chart using Helm: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm install $CRDBCLUSTER cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} -f values.yaml -n $NAMESPACE ``` You can override the default parameters using the `--set key=value[,key=value]` argument while installing the chart: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm install $CRDBCLUSTER cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} -f values.yaml --set clusterDomain=cluster-test.local -n $NAMESPACE ``` 4. Verify that the cluster has initialized and pods are now running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get pods -n $NAMESPACE ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAME READY STATUS RESTARTS AGE crdb-operator-655fbf7847-zn9v8 1/1 Running 0 10m cockroachdb-9swcg 2/2 Running 0 45s cockroachdb-bn6f7 2/2 Running 0 45s cockroachdb-nk2dw 2/2 Running 0 45s ``` #### Deploy across multiple regions The Helm chart supports specifying multiple region definitions in `cockroachdb.crdbCluster.regions` with their respective node counts. Make sure to review the prerequisites and best practices for a [multi-region deployment](#multi-region-deployments). For each region, modify the `regions` configuration as described in [Initialize the cluster](#initialize-the-cluster) and perform `helm install` against the respective Kubernetes cluster. The following example shows a configuration across two regions, `us-central1` and `us-east1`, with 3 nodes in each cluster: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: clusterDomain: cluster.gke.gcp-us-east1 crdbCluster: regions: - code: us-central1 nodes: 3 cloudProvider: gcp domain: cluster.gke.gcp-us-central1 namespace: cockroach-ns - code: us-east1 nodes: 3 cloudProvider: gcp domain: cluster.gke.gcp-us-east1 namespace: cockroach-ns ``` While applying the installation in a given region, do the following: * Verify that the domain matches `cockroachdb.clusterDomain` in the values file. * Ensure that `cockroachdb.crdbCluster.regions` captures the information for regions that have already been deployed, including the current region. This allows CockroachDB in the current region to connect to clusters deployed in the existing regions. ## Step 3. Use the built-in SQL client To use the CockroachDB SQL client, follow these steps to launch a secure pod running the `cockroach` binary. 1. Download the secure client Kubernetes application: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -O https://raw.githubusercontent.com/cockroachdb/helm-charts/master/examples/client-secure.yaml ``` > [!CAUTION] > > This client tool logs into CockroachDB as `root` using the root certificates. 1. Edit the yaml file with the following values: * `spec.serviceAccountName: my-release-cockroachdb` * `spec.image: cockroachdb/cockroach:` * `spec.volumes[0].project.sources[0].secret.name: my-release-cockroachdb-client-secret` 2. Launch a pod using this file and keep it running indefinitely: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create -f client-secure.yaml ``` 3. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # # Server version: CockroachDB CCL v21.1.0 (x86_64-unknown-linux-gnu, built 2021/04/23 13:54:57, go1.13.14) (same version as client) # Cluster ID: a96791d9-998c-4683-a3d3-edbf425bbf11 # # Enter \? for a brief introduction. # root@cockroachdb-public:26257/defaultdb> ``` This pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other cockroach client commands (e.g., cockroach node), repeat this step using the appropriate cockroach command. If you'd prefer to delete the pod and recreate it when needed, run `kubectl delete pod cockroachdb-client-secure`. 4. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE DATABASE bank; CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL); INSERT INTO bank.accounts VALUES (1, 1000.50); SELECT * FROM bank.accounts; id | balance +----+---------+ 1 | 1000.50 (1 row) ``` 5. [Create a user with a password](/docs/v26.4/create-user#create-a-user-with-a-password): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE USER roach WITH PASSWORD 'Q7gc8rEdS'; ``` You will need this username and password to access the DB Console later. 6. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} \q ``` ## Step 4. Access the DB Console To access the cluster's [DB Console](/docs/v26.4/ui-overview): 1. On secure clusters, [certain pages of the DB Console](/docs/v26.4/ui-overview#db-console-access) can only be accessed by `admin` users. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public ``` 2. Assign `roach` to the `admin` role (you only need to do this once): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} GRANT admin TO roach; ``` 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} \q ``` 4. In a new terminal window, port-forward from your local machine to the `cockroachdb-public` service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl port-forward service/cockroachdb-public 8080 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Forwarding from 127.0.0.1:8080 -> 8080 ``` Run the `port-forward` command on the same machine as the web browser in which you want to view the DB Console. If you have been running these commands from a cloud instance or other non-local shell, you will not be able to view the UI without configuring `kubectl` locally and running the preceding `port-forward` command on your local machine. 5. Go to [`https://localhost:8080`](https://localhost:8080/) and log in with the username and password you created earlier. > [!NOTE] > > If you are using Google Chrome, and get an error about not being able to reach `localhost` because its certificate has been revoked, go to `chrome://flags/#allow-insecure-localhost`, enable "Allow invalid certificates for resources loaded from localhost", and then restart the browser. This degrades security for all sites running on `localhost`, not just CockroachDB's DB Console, so enable the feature only temporarily. 1. In the DB Console, verify that the cluster is running as expected: 1. View the [**Node List**](/docs/v26.4/ui-cluster-overview-page#node-list) to ensure that all nodes successfully joined the cluster. 2. Click the **Databases** tab on the left to verify that `bank` is listed. ## Next steps Read the following pages for detailed information on cluster scaling, certificate management, resource management, best practices, and other cluster operation details: * [Pod scheduling](/docs/v26.4/schedule-cockroachdb-operator) * [Resource management](/docs/v26.4/configure-cockroachdb-operator) * [Certificate management](/docs/v26.4/secure-cockroachdb-operator) * [Cluster scaling](/docs/v26.4/scale-cockroachdb-operator) * [Cluster monitoring](/docs/v26.4/monitor-cockroachdb-operator) * [Upgrade a cluster](/docs/v26.4/upgrade-cockroachdb-operator) * [Override deployment templates](/docs/v26.4/override-templates-cockroachdb-operator) * [CockroachDB performance on Kubernetes](/docs/v26.4/cockroachdb-operator-performance) ## Examples ### Authenticate with `cockroach cert` The following example uses [cockroach cert commands](/docs/v26.4/cockroach-cert) to generate and sign the CockroachDB node and client certificates. To learn more about the supported methods of signing certificates, refer to [Authentication](/docs/v26.4/authentication#using-digital-certificates-with-cockroachdb). 1. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} mkdir certs my-safe-directory ``` 2. Create the CA certificate and key pair: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 3. Create a client certificate and key pair for the root user: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach cert create-client root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Upload the client certificate and key to the Kubernetes cluster as a secret, renaming them to the filenames required by the CockroachDB operator: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create secret generic cockroachdb.client.root \ --from-file=tls.key=certs/client.root.key \ --from-file=tls.crt=certs/client.root.crt \ --from-file=ca.crt=certs/ca.crt ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} secret/cockroachdb.client.root created ``` 5. Create the certificate and key pair for your CockroachDB nodes, specifying the namespace you used when deploying the cluster. This example uses the `cockroach-ns` namespace: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach cert create-node localhost \ 127.0.0.1 \ cockroachdb-public \ cockroachdb-public.cockroach-ns \ cockroachdb-public.cockroach-ns.svc.cluster.local \ *.cockroachdb \ *.cockroachdb.cockroach-ns \ *.cockroachdb.cockroach-ns.svc.cluster.local \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 6. Upload the node certificate and key to the Kubernetes cluster as a secret, renaming them to the filenames required by the CockroachDB operator: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create secret generic cockroachdb.node \ --from-file=tls.key=certs/node.key \ --from-file=tls.crt=certs/node.crt \ --from-file=ca.crt=certs/ca.crt ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} secret/cockroachdb.node created ``` 7. Check that the secrets were created on the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get secrets ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAME TYPE DATA AGE cockroachdb.client.root Opaque 3 13s cockroachdb.node Opaque 3 3s default-token-6js7b kubernetes.io/service-account-token 3 9h ``` 8. Add `cockroachdb.tls.externalCertificates.certificates.nodeSecretName` and `cockroachdb.tls.externalCertificates.certificates.nodeClientSecretName` to the values file used to deploy the cluster: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: tls: enabled: true externalCertificates: enabled: true certificates: nodeSecretName: cockroachdb.node nodeClientSecretName: cockroachdb.client.root ``` # Deploy CockroachDB in a Single Kubernetes Cluster Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-with-kubernetes > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). This page shows you how to start and stop a secure 3-node CockroachDB cluster in a single [Kubernetes](http://kubernetes.io/) cluster using the following approaches: * [Public operator](https://github.com/cockroachdb/cockroach-operator) The Public operator is also available on platforms such as [Red Hat OpenShift](/docs/v26.4/deploy-cockroachdb-with-kubernetes-openshift) and [IBM Cloud Pak for Data](https://www.ibm.com/products/cloud-pak-for-data). * Manual [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) configuration * [Helm](https://helm.sh/) package manager for Kubernetes > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. ## Best practices #### Kubernetes version To deploy CockroachDB v26.4, Kubernetes 1.18 or higher is required. Cockroach Labs strongly recommends that you use a Kubernetes version that is [eligible for patch support by the Kubernetes project](https://kubernetes.io/releases/). #### Public operator * The Public operator deploys clusters in a single region. For multi-region deployments using manual configs, Cockroach Labs recommends using the [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) which is designed to support multi-region deployments. For guidance on how to force multi-region support with the Public operator, see [Orchestrate CockroachDB Across Multiple Kubernetes Clusters](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster). * Using the Public operator, you can give a new cluster an arbitrary number of [labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/). However, a cluster's labels cannot be modified after it is deployed. To track the status of this limitation, refer to [#993](https://github.com/cockroachdb/cockroach-operator/issues/993) in the Public operator project's issue tracker. #### Helm version The CockroachDB Helm chart requires Helm 3.0 or higher. If you attempt to use an incompatible Helm version, an error like the following occurs: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Error: UPGRADE FAILED: template: cockroachdb/templates/tests/client.yaml:6:14: executing "cockroachdb/templates/tests/client.yaml" at <.Values.networkPolicy.enabled>: nil pointer evaluating interface {}.enabled ``` The public Helm chart is currently not under active development, and no new features are planned. However, Cockroach Labs remains committed to fully supporting the Helm chart by addressing defects, providing security patches, and addressing breaking changes due to deprecations in Kubernetes APIs. A deprecation notice for the public Helm chart will be provided to customers a minimum of 6 months in advance of actual deprecation. #### Network Service Name Indication (SNI) is an extension to the TLS protocol which allows a client to indicate which hostname it is attempting to connect to at the start of the TCP handshake process. The server can present multiple certificates on the same IP address and TCP port number, and one server can serve multiple secure websites or API services even if they use different certificates. Due to its order of operations, the PostgreSQL wire protocol's implementation of TLS is not compatible with SNI-based routing in the Kubernetes ingress controller. Instead, use a TCP load balancer for CockroachDB that is not shared with other services. #### Resources When starting Kubernetes, select machines with at least **4 vCPUs** and **16 GiB** of memory, and provision at least **2 vCPUs** and **8 Gi** of memory to CockroachDB per pod. These minimum settings are used by default in this deployment guide, and are appropriate for testing purposes only. On a production deployment, you should adjust the resource settings for your workload. For details, see [Resource management](/docs/v26.4/configure-cockroachdb-kubernetes#memory-and-cpu). #### Storage Kubernetes deployments use external persistent volumes that are often replicated by the provider. CockroachDB replicates data automatically, and this redundant layer of replication can impact performance. Using [local volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local) may improve performance. ## Step 1. Start Kubernetes You can use the hosted [Google Kubernetes Engine (GKE)](#hosted-gke) service or the hosted [Amazon Elastic Kubernetes Service (EKS)](#hosted-eks) to quickly start Kubernetes. > [!NOTE] > > GKE or EKS are not required to run CockroachDB on Kubernetes. A manual GCE or AWS cluster with the [minimum recommended Kubernetes version](#kubernetes-version) and at least 3 pods, each presenting [sufficient resources](#resources) to start a CockroachDB node, can also be used. > > You can also evaluate a CockroachDB Kubernetes deployment on a local machine with [minikube](https://minikube.sigs.k8s.io/docs/start/). ### Hosted GKE 1. Complete the **Before You Begin** steps described in the [Google Kubernetes Engine Quickstart](https://cloud.google.com/kubernetes-engine/docs/quickstart) documentation. This includes installing `gcloud`, which is used to create and delete Kubernetes Engine clusters, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. > [!TIP] > > The documentation offers the choice of using Google's Cloud Shell product or using a local shell on your machine. Choose to use a local shell if you want to be able to view the DB Console using the steps in this guide. 1. From your local workstation, start the Kubernetes cluster, specifying one of the available [regions](https://cloud.google.com/compute/docs/regions-zones#available) (e.g., `us-east1`): > [!TIP] > > Since this region can differ from your default `gcloud` region, be sure to include the `--region` flag to run `gcloud` commands against this cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters create cockroachdb --machine-type n2-standard-4 --region {region-name} --num-nodes 1 ``` ``` Creating cluster cockroachdb...done. ``` This creates GKE instances and joins them into a single Kubernetes cluster named `cockroachdb`. The `--region` flag specifies a [regional three-zone cluster](https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-regional-cluster), and `--num-nodes` specifies one Kubernetes worker node in each zone. The `--machine-type` flag tells the node pool to use the [`n2-standard-4`](https://cloud.google.com/compute/docs/machine-types#standard_machine_types) machine type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). The process can take a few minutes, so do not move on to the next step until you see a `Creating cluster cockroachdb...done` message and details about your cluster. 1. Get the email address associated with your Google Cloud account: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud info | grep Account ``` ``` Account: [your.google.cloud.email@example.org] ``` > [!CAUTION] > > This command returns your email address in all lowercase. However, in the next step, you must enter the address using the accurate capitalization. For example, if your address is [YourName@example.com](mailto:YourName@example.com), you must use [YourName@example.com](mailto:YourName@example.com) and not [yourname@example.com](mailto:yourname@example.com). 1. [Create the RBAC roles](https://cloud.google.com/kubernetes-engine/docs/how-to/role-based-access-control#prerequisites_for_using_role-based_access_control) CockroachDB needs for running on GKE, using the address from the previous step: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create clusterrolebinding $USER-cluster-admin-binding \ --clusterrole=cluster-admin \ --user={your.google.cloud.email@example.org} ``` ``` clusterrolebinding.rbac.authorization.k8s.io/your.username-cluster-admin-binding created ``` ### Hosted EKS 1. Complete the steps described in the [EKS Getting Started](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) documentation. This includes installing and configuring the AWS CLI and `eksctl`, which is the command-line tool used to create and delete Kubernetes clusters on EKS, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. > [!NOTE] > > If you are running [EKS-Anywhere](https://aws.amazon.com/eks/eks-anywhere/), CockroachDB requires that you [configure your default storage class](https://kubernetes.io/docs/tasks/administer-cluster/change-default-storage-class/) to auto-provision persistent volumes. Alternatively, you can define a custom storage configuration as required by your install pattern. 1. From your local workstation, start the Kubernetes cluster: > [!TIP] > > To ensure that all 3 nodes can be placed into a different availability zone, you may want to first [confirm that at least 3 zones are available in the region](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#availability-zones-describe) for your account. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl create cluster \ --name cockroachdb \ --nodegroup-name standard-workers \ --node-type m5.xlarge \ --nodes 3 \ --nodes-min 1 \ --nodes-max 4 \ --node-ami auto ``` This creates EKS instances and joins them into a single Kubernetes cluster named `cockroachdb`. The `--node-type` flag tells the node pool to use the [`m5.xlarge`](https://aws.amazon.com/ec2/instance-types/) instance type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). Cluster provisioning usually takes between 10 and 15 minutes. Do not move on to the next step until you see a message like `[✔] EKS cluster "cockroachdb" in "us-east-1" region is ready` and details about your cluster. 1. Open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) to verify that the stacks `eksctl-cockroachdb-cluster` and `eksctl-cockroachdb-nodegroup-standard-workers` were successfully created. Be sure that your region is selected in the console. ## Step 2. Start CockroachDB Choose how you want to deploy and maintain the CockroachDB cluster. > [!NOTE] > > The [Public Kubernetes operator](https://github.com/cockroachdb/cockroach-operator) eases CockroachDB cluster creation and management on a single Kubernetes cluster. The Public operator does not provision or apply a license key. To use CockroachDB with the Public operator, [set a license](/docs/v26.4/licensing-faqs#set-a-license) in the SQL shell. ### Install the Operator 1. Apply the [custom resource definition (CRD)](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/#customresourcedefinitions) for the Public operator: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/crds.yaml ``` ``` customresourcedefinition.apiextensions.k8s.io/crdbclusters.crdb.cockroachlabs.com created ``` 2. By default, the Public operator is configured to install in the `cockroach-operator-system` namespace and to manage CockroachDB instances for all namespaces on the cluster. * To use these defaults, apply the Public operator manifest without modifying it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml ``` ``` clusterrole.rbac.authorization.k8s.io/cockroach-database-role created serviceaccount/cockroach-database-sa created clusterrolebinding.rbac.authorization.k8s.io/cockroach-database-rolebinding created role.rbac.authorization.k8s.io/cockroach-operator-role created clusterrolebinding.rbac.authorization.k8s.io/cockroach-operator-rolebinding created clusterrole.rbac.authorization.k8s.io/cockroach-operator-role created serviceaccount/cockroach-operator-sa created rolebinding.rbac.authorization.k8s.io/cockroach-operator-default created deployment.apps/cockroach-operator created ``` * To change these defaults: 1. Download the Public operator manifest: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -O https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml ``` 2. To use a custom namespace, edit all instances of `namespace: cockroach-operator-system` with your desired namespace. 3. To limit the namespaces that will be monitored, set the `WATCH_NAMESPACE` environment variable in the `Deployment` pod spec. This can be set to a single namespace or a comma-delimited set of namespaces. When set, only those `CrdbCluster` resources in the supplied namespace(s) will be reconciled. 4. Apply your local version of the Public operator manifest to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f operator.yaml ``` 1. Set your current namespace to the one used by the Public operator. For example, to use the Public operator's default namespace: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl config set-context --current --namespace=cockroach-operator-system ``` 2. Validate that the operator is running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroach-operator-6f7b86ffc4-9ppkv 1/1 Running 0 54s ``` ### Initialize the cluster > [!NOTE] > > After a cluster managed by the Kubernetes operator is initialized, its Kubernetes labels cannot be modified. For more details, refer to [Best practices](#best-practices). 1. Download `example.yaml`, a custom resource that tells the operator how to configure the Kubernetes cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/examples/example.yaml ``` By default, this custom resource specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload. For details on configuring your deployment, see [Configure the Cluster](/docs/v26.4/configure-cockroachdb-kubernetes). > [!NOTE] > > By default, the operator will generate and sign 1 client and 1 node certificate to secure the cluster. This means that if you do not provide a CA, a `cockroach`-generated CA is used. If you want to authenticate using your own CA, [specify the generated secrets in the custom resource](/docs/v26.4/secure-cockroachdb-kubernetes#use-a-custom-ca) **before** proceeding to the next step. 1. Apply `example.yaml`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f example.yaml ``` The operator will create a StatefulSet and initialize the nodes as a cluster. ``` crdbcluster.crdb.cockroachlabs.com/cockroachdb created ``` 2. Check that the pods were created: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroach-operator-6f7b86ffc4-9t9zb 1/1 Running 0 3m22s cockroachdb-0 1/1 Running 0 2m31s cockroachdb-1 1/1 Running 0 102s cockroachdb-2 1/1 Running 0 46s ``` Each pod should have `READY` status soon after being created. ### Configure the cluster 1. Download and modify our [StatefulSet configuration](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/bring-your-own-certs/cockroachdb-statefulset.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/bring-your-own-certs/cockroachdb-statefulset.yaml ``` 2. Update `secretName` with the name of the corresponding node secret. The secret names depend on your method for generating secrets. For example, if you follow the below [steps using `cockroach cert`](#create-certificates), use this secret name: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} secret: secretName: cockroachdb.node ``` 3. The StatefulSet configuration deploys CockroachDB into the `default` namespace. To use a different namespace, search for `kind: RoleBinding` and change its `subjects.namespace` property to the name of the namespace. Otherwise, a `failed to read secrets` error occurs when you attempt to follow the steps in [Initialize the cluster](#initialize-the-cluster). > [!NOTE] > > By default, this manifest specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload. For details on configuring your deployment, see [Configure the Cluster](/docs/v26.4/configure-cockroachdb-kubernetes?filters=manual). ### Create certificates > [!TIP] > > The StatefulSet configuration sets all CockroachDB nodes to log to `stderr`, so if you ever need access to a pod/node's logs to troubleshoot, use `kubectl logs ` rather than checking the log on the persistent volume. The below steps use [`cockroach cert` commands](/docs/v26.4/cockroach-cert) to quickly generate and sign the CockroachDB node and client certificates. Read our [Authentication](/docs/v26.4/authentication#using-digital-certificates-with-cockroachdb) docs to learn about other methods of signing certificates. 1. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs my-safe-directory ``` | Directory | Description | | - | - | | `certs` | You'll generate your CA certificate and all node and client certificates and keys in this directory. | | `my-safe-directory` | You'll generate your CA key in this directory and then reference the key when generating node and client certificates. | 2. Create the CA certificate and key pair: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 3. Create a client certificate and key pair for the root user: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-client \ root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. Upload the client certificate and key to the Kubernetes cluster as a secret: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create secret \ generic cockroachdb.client.root \ --from-file=certs ``` ``` secret/cockroachdb.client.root created ``` 5. Create the certificate and key pair for your CockroachDB nodes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ localhost 127.0.0.1 \ cockroachdb-public \ cockroachdb-public.default \ cockroachdb-public.default.svc.cluster.local \ *.cockroachdb \ *.cockroachdb.default \ *.cockroachdb.default.svc.cluster.local \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 6. Upload the node certificate and key to the Kubernetes cluster as a secret: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create secret \ generic cockroachdb.node \ --from-file=certs ``` ``` secret/cockroachdb.node created ``` 7. Check that the secrets were created on the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get secrets ``` ``` NAME TYPE DATA AGE cockroachdb.client.root Opaque 3 41m cockroachdb.node Opaque 5 14s default-token-6qjdb kubernetes.io/service-account-token 3 4m ``` ### Initialize the cluster 1. Use the config file you downloaded to create the StatefulSet that automatically creates 3 pods, each running a CockroachDB node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f cockroachdb-statefulset.yaml ``` ``` serviceaccount/cockroachdb created role.rbac.authorization.k8s.io/cockroachdb created rolebinding.rbac.authorization.k8s.io/cockroachdb created service/cockroachdb-public created service/cockroachdb created poddisruptionbudget.policy/cockroachdb-budget created statefulset.apps/cockroachdb created ``` 2. Initialize the CockroachDB cluster: 1. Confirm that three pods are `Running` successfully. Note that they will not be considered `Ready` until after the cluster has been initialized: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-0 0/1 Running 0 2m cockroachdb-1 0/1 Running 0 2m cockroachdb-2 0/1 Running 0 2m ``` 2. Confirm that the persistent volumes and corresponding claims were created successfully for all three pods: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pv ``` ``` NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-9e435563-fb2e-11e9-a65c-42010a8e0fca 100Gi RWO Delete Bound default/datadir-cockroachdb-0 standard 51m pvc-9e47d820-fb2e-11e9-a65c-42010a8e0fca 100Gi RWO Delete Bound default/datadir-cockroachdb-1 standard 51m pvc-9e4f57f0-fb2e-11e9-a65c-42010a8e0fca 100Gi RWO Delete Bound default/datadir-cockroachdb-2 standard 51m ``` 3. Run `cockroach init` on one of the pods to complete the node startup process and have them join together as a cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-0 \ -- /cockroach/cockroach init \ --certs-dir=/cockroach/cockroach-certs ``` ``` Cluster successfully initialized ``` 4. Confirm that cluster initialization has completed successfully. The job should be considered successful and the Kubernetes pods should soon be considered `Ready`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-0 1/1 Running 0 3m cockroachdb-1 1/1 Running 0 3m cockroachdb-2 1/1 Running 0 3m ``` The CockroachDB Helm chart is compatible with all Kubernetes versions that are [supported by the Kubernetes project](https://kubernetes.io/releases/) when cert-manager is used for mTLS. The CockroachDB Helm chart is currently not under active development, and no new features are planned. However, Cockroach Labs remains committed to fully supporting the Helm chart by addressing defects, providing security patches, and addressing breaking changes due to deprecations in Kubernetes APIs. A deprecation notice for the Helm chart will be provided to customers a minimum of 6 months in advance of actual deprecation. > [!CAUTION] > > If you are running a secure Helm deployment on Kubernetes 1.22 and later, you must migrate away from using the Kubernetes CA for cluster authentication. The recommended approach is to use `cert-manager` for certificate management. For details, refer to [Deploy cert-manager for mTLS](/docs/v26.4/secure-cockroachdb-kubernetes?filters=helm#deploy-cert-manager-for-mtls). 1. [Install the Helm client](https://helm.sh/docs/intro/install) (version 3.0 or higher) and add the `cockroachdb` chart repository: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm repo add cockroachdb https://charts.cockroachdb.com/ ``` ``` "cockroachdb" has been added to your repositories ``` 2. Update your Helm chart repositories to ensure that you're using the [latest CockroachDB chart](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/Chart.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm repo update ``` 3. The cluster configuration is set in the Helm chart's [values file](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml). > [!NOTE] > > By default, the Helm chart specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload. For details on configuring your deployment, see [Configure the Cluster](/docs/v26.4/configure-cockroachdb-kubernetes?filters=helm). Before deploying, modify some parameters in our Helm chart's [values file](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml): 1. Create a local YAML file (e.g., `my-values.yaml`) to specify your custom values. These will be used to override the defaults in `values.yaml`. 2. To avoid running out of memory when CockroachDB is not the only pod on a Kubernetes node, you *must* set memory limits explicitly. This is because CockroachDB does not detect the amount of memory allocated to its pod when run in Kubernetes. We recommend setting `conf.cache` and `conf.max-sql-memory` each to 1/4 of the `memory` allocation specified in `statefulset.resources.requests` and `statefulset.resources.limits`. > [!TIP] > > For example, if you are allocating 8Gi of `memory` to each CockroachDB node, allocate 2Gi to `cache` and 2Gi to `max-sql-memory`. ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} conf: cache: "2Gi" max-sql-memory: "2Gi" ``` The Helm chart defaults to a secure deployment by automatically setting `tls.enabled` to `true`. > [!NOTE] > > By default, the Helm chart will generate and sign 1 client and 1 node certificate to secure the cluster. To authenticate using your own CA, see [Certificate management](/docs/v26.4/secure-cockroachdb-kubernetes?filters=helm#use-a-custom-ca). Refer to the [CockroachDB Helm chart's `values.yaml` template](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml). 1. Install the CockroachDB Helm chart, specifying your custom values file. Provide a "release" name to identify and track this particular deployment of the chart, and override the default values with those in `my-values.yaml`. > [!NOTE] > > This tutorial uses `my-release` as the release name. If you use a different value, be sure to adjust the release name in subsequent commands. > [!CAUTION] > > To allow the CockroachDB pods to successfully deploy, do not set the [`--wait` flag](https://helm.sh/docs/intro/using_helm/#helpful-options-for-installupgraderollback) when using Helm commands. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm install my-release --values {custom-values}.yaml cockroachdb/cockroachdb ``` Behind the scenes, this command uses our `cockroachdb-statefulset.yaml` file to create the StatefulSet that automatically creates 3 pods, each with a CockroachDB node running inside it, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart. 1. Confirm that CockroachDB cluster initialization has completed successfully, with the pods for CockroachDB showing `1/1` under `READY` and the pod for initialization showing `COMPLETED` under `STATUS`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE my-release-cockroachdb-0 1/1 Running 0 8m my-release-cockroachdb-1 1/1 Running 0 8m my-release-cockroachdb-2 1/1 Running 0 8m my-release-cockroachdb-init-hxzsc 0/1 Completed 0 1h ``` 2. Confirm that the persistent volumes and corresponding claims were created successfully for all three pods: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pv ``` ``` NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-71019b3a-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-0 standard 11m pvc-7108e172-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-1 standard 11m pvc-710dcb66-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-2 standard 11m ``` The StatefulSet configuration sets all CockroachDB nodes to log to `stderr`, so if you ever need access to logs for a pod, use `kubectl logs ` rather than checking the log on the persistent volume. ## Step 3. Use the built-in SQL client To use the CockroachDB SQL client, first launch a secure pod running the `cockroach` binary. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create \ -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/examples/client-secure-operator.yaml ``` 1. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public ``` ``` # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # # Server version: CockroachDB CCL v21.1.0 (x86_64-unknown-linux-gnu, built 2021/04/23 13:54:57, go1.13.14) (same version as client) # Cluster ID: a96791d9-998c-4683-a3d3-edbf425bbf11 # # Enter \? for a brief introduction. # root@cockroachdb-public:26257/defaultdb> ``` 2. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE bank; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO bank.accounts VALUES (1, 1000.50); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.accounts; ``` ``` id | balance +----+---------+ 1 | 1000.50 (1 row) ``` 3. [Create a user with a password](/docs/v26.4/create-user#create-a-user-with-a-password): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS'; ``` You will need this username and password to access the DB Console later. 4. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create \ -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/bring-your-own-certs/client.yaml ``` ``` pod/cockroachdb-client-secure created ``` 1. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach-certs \ --host=cockroachdb-public ``` ``` # Welcome to the cockroach SQL interface. # All statements must be terminated by a semicolon. # To exit: CTRL + D. # # Client version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Server version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Cluster ID: 256a8705-e348-4e3a-ab12-e1aba96857e4 # # Enter \? for a brief introduction. # root@cockroachdb-public:26257/defaultdb> ``` > [!TIP] > > This pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other [`cockroach` client commands](/docs/v26.4/cockroach-commands) (e.g., `cockroach node`), repeat step 2 using the appropriate `cockroach` command. > > If you'd prefer to delete the pod and recreate it when needed, run `kubectl delete pod cockroachdb-client-secure`. 1. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE bank; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO bank.accounts VALUES (1, 1000.50); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.accounts; ``` ``` id | balance +----+---------+ 1 | 1000.50 (1 row) ``` 2. [Create a user with a password](/docs/v26.4/create-user#create-a-user-with-a-password): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS'; ``` You will need this username and password to access the DB Console later. 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` From your local workstation, use our [`client-secure.yaml`](https://github.com/cockroachdb/helm-charts/blob/master/examples/client-secure.yaml) file to launch a pod and keep it running indefinitely. 1. Download the file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -OOOOOOOOO \ https://raw.githubusercontent.com/cockroachdb/helm-charts/master/examples/client-secure.yaml ``` 2. In the file, set the following values: * `spec.serviceAccountName: my-release-cockroachdb` * `spec.image: cockroachdb/cockroach: {your CockroachDB version}` * `spec.volumes[0].project.sources[0].secret.name: my-release-cockroachdb-client-secret` 3. Use the file to launch a pod and keep it running indefinitely: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f client-secure.yaml ``` ``` pod "cockroachdb-client-secure" created ``` 4. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=./cockroach-certs \ --host=my-release-cockroachdb-public ``` ``` # Welcome to the cockroach SQL interface. # All statements must be terminated by a semicolon. # To exit: CTRL + D. # # Client version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Server version: CockroachDB CCL v19.1.0 (x86_64-unknown-linux-gnu, built 2019/04/29 18:36:40, go1.11.6) # Cluster ID: 256a8705-e348-4e3a-ab12-e1aba96857e4 # # Enter \? for a brief introduction. # root@my-release-cockroachdb-public:26257/defaultdb> ``` This pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other [`cockroach` client commands](/docs/v26.4/cockroach-commands) (e.g., `cockroach node`), repeat step 2 using the appropriate `cockroach` command. If you'd prefer to delete the pod and recreate it when needed, run `kubectl delete pod cockroachdb-client-secure`. 5. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE bank; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO bank.accounts VALUES (1, 1000.50); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.accounts; ``` ``` id | balance +----+---------+ 1 | 1000.50 (1 row) ``` 6. [Create a user with a password](/docs/v26.4/create-user#create-a-user-with-a-password): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS'; ``` You will need this username and password to access the DB Console later. 7. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ## Step 4. Access the DB Console To access the cluster's [DB Console](/docs/v26.4/ui-overview): 1. On secure clusters, [certain pages of the DB Console](/docs/v26.4/ui-overview#db-console-access) can only be accessed by `admin` users. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach-certs \ --host=cockroachdb-public ``` \$ kubectl exec -it cockroachdb-client-secure \ \-- ./cockroach sql \ \--certs-dir=/cockroach-certs \ \--host=my-release-cockroachdb-public 2. Assign `roach` to the `admin` role (you only need to do this once): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > GRANT admin TO roach; ``` 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` 4. In a new terminal window, port-forward from your local machine to the `cockroachdb-public` service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward service/cockroachdb-public 8080 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward service/cockroachdb-public 8080 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward service/my-release-cockroachdb-public 8080 ``` ``` Forwarding from 127.0.0.1:8080 -> 8080 ``` 5. Go to [https://localhost:8080](https://localhost:8080) and log in with the username and password you created earlier. If you are using Google Chrome, and you are getting an error about not being able to reach `localhost` because its certificate has been revoked, go to chrome://flags/#allow-insecure-localhost, enable "Allow invalid certificates for resources loaded from localhost", and then restart the browser. Enabling this Chrome feature degrades security for all sites running on `localhost`, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily. 1. Go to [http://localhost:8080](http://localhost:8080). 2. In the UI, verify that the cluster is running as expected: * View the [Node List](/docs/v26.4/ui-cluster-overview-page#node-list) to ensure that all nodes successfully joined the cluster. * Click the **Databases** tab on the left to verify that `bank` is listed. ## Step 5. Stop the cluster > [!NOTE] > > If you want to continue using this cluster, refer the documentation on [configuring](/docs/v26.4/configure-cockroachdb-kubernetes), [scaling](/docs/v26.4/scale-cockroachdb-kubernetes), [monitoring](/docs/v26.4/monitor-cockroachdb-kubernetes), and [upgrading](/docs/v26.4/upgrade-cockroachdb-kubernetes) the cluster. To shut down the CockroachDB cluster: 1. Delete the previously created custom resource: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete -f example.yaml ``` 2. Remove the Public operator: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml ``` This will delete the CockroachDB cluster being run by the Public operator. It intentionally does **not** delete: * The persistent volumes that were attached to the pods, to avoid the risk of data loss. Before deleting a cluster's persistent volumes, be sure to back them up. For more information, refer to [Delete a Cluster's Persistent Volumes](#delete-a-cluster’s-persistent-volumes) in the Kubernetes project's documentation. * Any secrets you may have created. For more information on managing secrets, refer to [Managing Secrets Using `kubectl`](https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl) in the Kubernetes project's documentation. This procedure shuts down the CockroachDB cluster and deletes the resources you just created, including the logs and Prometheus and Alertmanager resources. This command intentionally does **not** delete: * The persistent volumes that were attached to the pods, to avoid the risk of data loss. Before deleting a cluster's persistent volumes, be sure to back them up. For more information, refer to [Delete a Cluster's Persistent Volumes](#delete-a-cluster’s-persistent-volumes) in the Kubernetes project's documentation. * Any secrets you may have created. For more information on managing secrets, refer to [Managing Secrets Using `kubectl`](https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl) in the Kubernetes project's documentation. > [!CAUTION] > > Do **not** use the `--all` flag to `kubectl delete`, to avoid the risk of data loss. 1. Delete the resources associated with the `cockroachdb` label, including the logs and Prometheus and Alertmanager resources. This command is very long; you may need to scroll your browser to read all of it. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete \ pods,statefulsets,services,poddisruptionbudget,jobs,rolebinding,clusterrolebinding,role,clusterrole,serviceaccount,alertmanager,prometheus,prometheusrule,serviceMonitor \ -l app=cockroachdb ``` ``` pod "cockroachdb-0" deleted pod "cockroachdb-1" deleted pod "cockroachdb-2" deleted statefulset.apps "alertmanager-cockroachdb" deleted statefulset.apps "prometheus-cockroachdb" deleted service "alertmanager-cockroachdb" deleted service "cockroachdb" deleted service "cockroachdb-public" deleted poddisruptionbudget.policy "cockroachdb-budget" deleted job.batch "cluster-init-secure" deleted rolebinding.rbac.authorization.k8s.io "cockroachdb" deleted clusterrolebinding.rbac.authorization.k8s.io "cockroachdb" deleted clusterrolebinding.rbac.authorization.k8s.io "prometheus" deleted role.rbac.authorization.k8s.io "cockroachdb" deleted clusterrole.rbac.authorization.k8s.io "cockroachdb" deleted clusterrole.rbac.authorization.k8s.io "prometheus" deleted serviceaccount "cockroachdb" deleted serviceaccount "prometheus" deleted alertmanager.monitoring.coreos.com "cockroachdb" deleted prometheus.monitoring.coreos.com "cockroachdb" deleted prometheusrule.monitoring.coreos.com "prometheus-cockroachdb-rules" deleted servicemonitor.monitoring.coreos.com "cockroachdb" deleted ``` 2. Delete the pod created for `cockroach` client commands, if you didn't do so earlier: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete pod cockroachdb-client-secure ``` ``` pod "cockroachdb-client-secure" deleted ``` 3. Delete the cluster's cryptographic resources. * If your cluster's certificates are managed using `cert-manager` (recommended but not default), get the names of the cluster's `issuers` and delete them: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get issuer ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete issuer {issuer_name} ``` * If your cluster uses self-signed certificates (the default), get the names of any CSRs for the cluster, then delete them: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get csr ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete csr default.client.root default.{node_name} ``` 1. Uninstall the release: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm uninstall my-release ``` ``` release "my-release" deleted ``` 2. Delete the pod created for `cockroach` client commands, if you didn't do so earlier: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete pod cockroachdb-client-secure ``` ``` pod "cockroachdb-client-secure" deleted ``` 3. Delete the cluster's cryptographic resources. * If your cluster's certificates are managed using `cert-manager` (recommended but not default), get the names of the cluster's `issuers` and delete them: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get issuer ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete issuer {issuer_name} ``` * If your cluster uses self-signed certificates (the default), get the names of any CSRs for the cluster, then delete them: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get csr ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete csr default.client.root default.{node_name} ``` ### Delete a cluster's persistent volumes If you need to free up the storage used by CockroachDB, you can optionally delete the persistent volumes that were attached to the pods, after first backing up your data. > [!CAUTION] > > Before you delete a cluster's persistent volumes, be sure you have a backup copy of your data. Data **cannot** be recovered once the persistent volumes are deleted. For more information, see the [Kubernetes documentation](https://kubernetes.io/docs/tasks/run-application/delete-stateful-set/#persistent-volumes). Refer to the Kubernetes project's documentation for more information and recommendations. ### Stop Kubernetes To delete the Kubernetes cluster: * Hosted GKE: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters delete cockroachdb --region {region-name} ``` * Hosted EKS: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl delete cluster --name cockroachdb ``` * Manual GCE: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cluster/kube-down.sh ``` * Manual AWS: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cluster/kube-down.sh ``` > [!CAUTION] > > If you stop Kubernetes without first deleting the persistent volumes, they will still exist in your cloud project. ## See also * [Resource management](/docs/v26.4/configure-cockroachdb-kubernetes) * [Certificate management](/docs/v26.4/secure-cockroachdb-kubernetes) * [Cluster monitoring](/docs/v26.4/monitor-cockroachdb-kubernetes) * [Kubernetes Multi-Cluster Deployment](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster) * [Optimize Performance on Kubernetes](/docs/v26.4/kubernetes-performance) * [Production Checklist](/docs/v26.4/recommended-production-settings) # Deploy CockroachDB in a Single Kubernetes Cluster (Insecure) Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-with-kubernetes-insecure This page shows you how to start and stop a 3-node CockroachDB insecure test cluster in a single [Kubernetes](http://kubernetes.io/) cluster, using one of the following: * Manual [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) configuration * [Helm](https://helm.sh/) package manager for Kubernetes > [!CAUTION] > > The `--insecure` flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead. The steps below demonstrate how to quickly deploy and interact with an insecure test cluster. To learn about authenticating, configuring, scaling, and upgrading a CockroachDB cluster on Kubernetes, see [Kubernetes Overview](/docs/v26.4/kubernetes-overview). > [!TIP] > > To try CockroachDB Cloud instead of running CockroachDB yourself, refer to the Cloud Quickstart. ## Before you begin Before getting started, it's helpful to review some Kubernetes-specific terminology and current limitations. * [Kubernetes terminology](#kubernetes-terminology) * [Best practices](#best-practices) ### Kubernetes terminology | Feature | Description | | - | - | | [node](https://kubernetes.io/docs/concepts/architecture/nodes/) | A physical or virtual machine. In this tutorial, you'll create GCE or AWS instances and join them as worker nodes into a single Kubernetes cluster from your local workstation. | | [pod](http://kubernetes.io/docs/user-guide/pods/) | A pod is a group of one or more Docker containers. In this tutorial, each pod will run on a separate Kubernetes node and include one Docker container running a single CockroachDB node. You'll start with 3 pods and grow to 4. | | [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) | A StatefulSet is a group of pods treated as stateful units, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart. StatefulSets are considered stable as of Kubernetes version 1.9 after reaching beta in version 1.5. | | [persistent volumes](http://kubernetes.io/docs/user-guide/persistent-volumes/) | A persistent volume is a piece of networked storage (Persistent Disk on GCE, Elastic Block Store on AWS) mounted into a pod. The lifetime of a persistent volume is decoupled from the lifetime of the pod that's using it, ensuring that each CockroachDB node binds back to the same storage on restart. This tutorial assumes that dynamic volume provisioning is available. When that is not the case, [persistent volume claims](http://kubernetes.io/docs/user-guide/persistent-volumes/#persistentvolumeclaims) need to be created manually. | ### Best practices #### Kubernetes version To deploy CockroachDB v26.4, Kubernetes 1.18 or higher is required. Cockroach Labs strongly recommends that you use a Kubernetes version that is [eligible for patch support by the Kubernetes project](https://kubernetes.io/releases/). #### Public operator * The Public operator deploys clusters in a single region. For multi-region deployments using manual configs, Cockroach Labs recommends using the [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) which is designed to support multi-region deployments. For guidance on how to force multi-region support with the Public operator, see [Orchestrate CockroachDB Across Multiple Kubernetes Clusters](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster). * Using the Public operator, you can give a new cluster an arbitrary number of [labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/). However, a cluster's labels cannot be modified after it is deployed. To track the status of this limitation, refer to [#993](https://github.com/cockroachdb/cockroach-operator/issues/993) in the Public operator project's issue tracker. #### Helm version The CockroachDB Helm chart requires Helm 3.0 or higher. If you attempt to use an incompatible Helm version, an error like the following occurs: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Error: UPGRADE FAILED: template: cockroachdb/templates/tests/client.yaml:6:14: executing "cockroachdb/templates/tests/client.yaml" at <.Values.networkPolicy.enabled>: nil pointer evaluating interface {}.enabled ``` The public Helm chart is currently not under active development, and no new features are planned. However, Cockroach Labs remains committed to fully supporting the Helm chart by addressing defects, providing security patches, and addressing breaking changes due to deprecations in Kubernetes APIs. A deprecation notice for the public Helm chart will be provided to customers a minimum of 6 months in advance of actual deprecation. #### Network Service Name Indication (SNI) is an extension to the TLS protocol which allows a client to indicate which hostname it is attempting to connect to at the start of the TCP handshake process. The server can present multiple certificates on the same IP address and TCP port number, and one server can serve multiple secure websites or API services even if they use different certificates. Due to its order of operations, the PostgreSQL wire protocol's implementation of TLS is not compatible with SNI-based routing in the Kubernetes ingress controller. Instead, use a TCP load balancer for CockroachDB that is not shared with other services. #### Resources When starting Kubernetes, select machines with at least **4 vCPUs** and **16 GiB** of memory, and provision at least **2 vCPUs** and **8 Gi** of memory to CockroachDB per pod. These minimum settings are used by default in this deployment guide, and are appropriate for testing purposes only. On a production deployment, you should adjust the resource settings for your workload. For details, see [Resource management](/docs/v26.4/configure-cockroachdb-kubernetes#memory-and-cpu). #### Storage Kubernetes deployments use external persistent volumes that are often replicated by the provider. CockroachDB replicates data automatically, and this redundant layer of replication can impact performance. Using [local volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local) may improve performance. ## Step 1. Start Kubernetes You can use the hosted [Google Kubernetes Engine (GKE)](#hosted-gke) service or the hosted [Amazon Elastic Kubernetes Service (EKS)](#hosted-eks) to quickly start Kubernetes. > [!NOTE] > > GKE or EKS are not required to run CockroachDB on Kubernetes. A manual GCE or AWS cluster with the [minimum recommended Kubernetes version](#kubernetes-version) and at least 3 pods, each presenting [sufficient resources](#resources) to start a CockroachDB node, can also be used. > > You can also evaluate a CockroachDB Kubernetes deployment on a local machine with [minikube](https://minikube.sigs.k8s.io/docs/start/). ### Hosted GKE 1. Complete the **Before You Begin** steps described in the [Google Kubernetes Engine Quickstart](https://cloud.google.com/kubernetes-engine/docs/quickstart) documentation. This includes installing `gcloud`, which is used to create and delete Kubernetes Engine clusters, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. > [!TIP] > > The documentation offers the choice of using Google's Cloud Shell product or using a local shell on your machine. Choose to use a local shell if you want to be able to view the DB Console using the steps in this guide. 1. From your local workstation, start the Kubernetes cluster, specifying one of the available [regions](https://cloud.google.com/compute/docs/regions-zones#available) (e.g., `us-east1`): > [!TIP] > > Since this region can differ from your default `gcloud` region, be sure to include the `--region` flag to run `gcloud` commands against this cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters create cockroachdb --machine-type n2-standard-4 --region {region-name} --num-nodes 1 ``` ``` Creating cluster cockroachdb...done. ``` This creates GKE instances and joins them into a single Kubernetes cluster named `cockroachdb`. The `--region` flag specifies a [regional three-zone cluster](https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-regional-cluster), and `--num-nodes` specifies one Kubernetes worker node in each zone. The `--machine-type` flag tells the node pool to use the [`n2-standard-4`](https://cloud.google.com/compute/docs/machine-types#standard_machine_types) machine type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). The process can take a few minutes, so do not move on to the next step until you see a `Creating cluster cockroachdb...done` message and details about your cluster. 1. Get the email address associated with your Google Cloud account: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud info | grep Account ``` ``` Account: [your.google.cloud.email@example.org] ``` > [!CAUTION] > > This command returns your email address in all lowercase. However, in the next step, you must enter the address using the accurate capitalization. For example, if your address is [YourName@example.com](mailto:YourName@example.com), you must use [YourName@example.com](mailto:YourName@example.com) and not [yourname@example.com](mailto:yourname@example.com). 1. [Create the RBAC roles](https://cloud.google.com/kubernetes-engine/docs/how-to/role-based-access-control#prerequisites_for_using_role-based_access_control) CockroachDB needs for running on GKE, using the address from the previous step: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create clusterrolebinding $USER-cluster-admin-binding \ --clusterrole=cluster-admin \ --user={your.google.cloud.email@example.org} ``` ``` clusterrolebinding.rbac.authorization.k8s.io/your.username-cluster-admin-binding created ``` ### Hosted EKS 1. Complete the steps described in the [EKS Getting Started](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) documentation. This includes installing and configuring the AWS CLI and `eksctl`, which is the command-line tool used to create and delete Kubernetes clusters on EKS, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. > [!NOTE] > > If you are running [EKS-Anywhere](https://aws.amazon.com/eks/eks-anywhere/), CockroachDB requires that you [configure your default storage class](https://kubernetes.io/docs/tasks/administer-cluster/change-default-storage-class/) to auto-provision persistent volumes. Alternatively, you can define a custom storage configuration as required by your install pattern. 1. From your local workstation, start the Kubernetes cluster: > [!TIP] > > To ensure that all 3 nodes can be placed into a different availability zone, you may want to first [confirm that at least 3 zones are available in the region](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#availability-zones-describe) for your account. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl create cluster \ --name cockroachdb \ --nodegroup-name standard-workers \ --node-type m5.xlarge \ --nodes 3 \ --nodes-min 1 \ --nodes-max 4 \ --node-ami auto ``` This creates EKS instances and joins them into a single Kubernetes cluster named `cockroachdb`. The `--node-type` flag tells the node pool to use the [`m5.xlarge`](https://aws.amazon.com/ec2/instance-types/) instance type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). Cluster provisioning usually takes between 10 and 15 minutes. Do not move on to the next step until you see a message like `[✔] EKS cluster "cockroachdb" in "us-east-1" region is ready` and details about your cluster. 1. Open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) to verify that the stacks `eksctl-cockroachdb-cluster` and `eksctl-cockroachdb-nodegroup-standard-workers` were successfully created. Be sure that your region is selected in the console. ## Step 2. Start CockroachDB Choose how you want to deploy and maintain the CockroachDB cluster. 1. From your local workstation, use our [`cockroachdb-statefulset.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cockroachdb-statefulset.yaml) file to create the StatefulSet that automatically creates 3 pods, each with a CockroachDB node running inside it. Download [`cockroachdb-statefulset.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cockroachdb-statefulset.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cockroachdb-statefulset.yaml ``` > [!NOTE] > > By default, this manifest specifies CPU and memory resources that are appropriate for the virtual machines used in this deployment example. On a production cluster, you should substitute values that are appropriate for your machines and workload. For details on configuring your deployment, see [Resource management](/docs/v26.4/configure-cockroachdb-kubernetes?filters=manual). Use the file to create the StatefulSet and start the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f cockroachdb-statefulset.yaml ``` ``` service/cockroachdb-public created service/cockroachdb created poddisruptionbudget.policy/cockroachdb-budget created statefulset.apps/cockroachdb created ``` Alternatively, if you'd rather start with a configuration file that has been customized for performance: 1. Download our [performance version of `cockroachdb-statefulset-insecure.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/performance/cockroachdb-statefulset-insecure.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/performance/cockroachdb-statefulset-insecure.yaml ``` 2. Modify the file wherever there is a `TODO` comment. 3. Use the file to create the StatefulSet and start the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f cockroachdb-statefulset-insecure.yaml ``` 4. Confirm that three pods are `Running` successfully. Note that they will not be considered `Ready` until after the cluster has been initialized: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-0 0/1 Running 0 2m cockroachdb-1 0/1 Running 0 2m cockroachdb-2 0/1 Running 0 2m ``` 5. Confirm that the persistent volumes and corresponding claims were created successfully for all three pods: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get persistentvolumes ``` ``` NAME CAPACITY ACCESSMODES RECLAIMPOLICY STATUS CLAIM REASON AGE pvc-52f51ecf-8bd5-11e6-a4f4-42010a800002 1Gi RWO Delete Bound default/datadir-cockroachdb-0 26s pvc-52fd3a39-8bd5-11e6-a4f4-42010a800002 1Gi RWO Delete Bound default/datadir-cockroachdb-1 27s pvc-5315efda-8bd5-11e6-a4f4-42010a800002 1Gi RWO Delete Bound default/datadir-cockroachdb-2 27s ``` 6. Use our [`cluster-init.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cluster-init.yaml) file to perform a one-time initialization that joins the CockroachDB nodes into a single cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create \ -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cluster-init.yaml ``` ``` job.batch/cluster-init created ``` 7. Confirm that cluster initialization has completed successfully. The job should be considered successful and the Kubernetes pods should soon be considered `Ready`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get job cluster-init ``` ``` NAME COMPLETIONS DURATION AGE cluster-init 1/1 7s 27s ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE cluster-init-cqf8l 0/1 Completed 0 56s cockroachdb-0 1/1 Running 0 7m51s cockroachdb-1 1/1 Running 0 7m51s cockroachdb-2 1/1 Running 0 7m51s ``` > [!TIP] > > The StatefulSet configuration sets all CockroachDB nodes to log to `stderr`, so if you ever need access to a pod/node's logs to troubleshoot, use `kubectl logs ` rather than checking the log on the persistent volume. 1. [Install the Helm client](https://helm.sh/docs/intro/install) (version 3.0 or higher) and add the `cockroachdb` chart repository: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm repo add cockroachdb https://charts.cockroachdb.com/ ``` ``` "cockroachdb" has been added to your repositories ``` 2. Update your Helm chart repositories to ensure that you're using the [latest CockroachDB chart](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/Chart.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm repo update ``` 3. Modify our Helm chart's [`values.yaml`](https://github.com/cockroachdb/helm-charts/blob/master/cockroachdb-legacy/values.yaml) parameters for your deployment scenario. Create a `my-values.yaml` file to override the defaults in `values.yaml`, substituting your own values in this example based on the guidelines below. ``` statefulset: resources: limits: memory: "8Gi" requests: memory: "8Gi" conf: cache: "2Gi" max-sql-memory: "2Gi" ``` 1. To avoid running out of memory when CockroachDB is not the only pod on a Kubernetes node, you *must* set memory limits explicitly. This is because CockroachDB does not detect the amount of memory allocated to its pod when run in Kubernetes. We recommend setting `conf.cache` and `conf.max-sql-memory` each to 1/4 of the `memory` allocation specified in `statefulset.resources.requests` and `statefulset.resources.limits`. > [!TIP] > > For example, if you are allocating 8Gi of `memory` to each CockroachDB node, allocate 2Gi to `cache` and 2Gi to `max-sql-memory`. 1. For an insecure deployment, set `tls.enabled` to `false`. For clarity, this example includes the example configuration from the previous steps. ``` statefulset: resources: limits: memory: "8Gi" requests: memory: "8Gi" conf: cache: "2Gi" max-sql-memory: "2Gi" tls: enabled: false ``` 1. You may want to modify `storage.persistentVolume.size` and `storage.persistentVolume.storageClass` for your use case. This chart defaults to 100Gi of disk space per pod. For more details on customizing disks for performance, see [these instructions](/docs/v26.4/kubernetes-performance#disk-type). > [!NOTE] > > If necessary, you can [expand disk size](/docs/v26.4/configure-cockroachdb-kubernetes?filters=helm#expand-disk-size) after the cluster is live. 1. Install the CockroachDB Helm chart. Provide a "release" name to identify and track this particular deployment of the chart, and override the default values with those in `my-values.yaml`. > [!NOTE] > > This tutorial uses `my-release` as the release name. If you use a different value, be sure to adjust the release name in subsequent commands. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm install my-release --values my-values.yaml cockroachdb/cockroachdb ``` Behind the scenes, this command uses our `cockroachdb-statefulset.yaml` file to create the StatefulSet that automatically creates 3 pods, each with a CockroachDB node running inside it, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart. 1. Confirm that CockroachDB cluster initialization has completed successfully, with the pods for CockroachDB showing `1/1` under `READY` and the pod for initialization showing `COMPLETED` under `STATUS`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods ``` ``` NAME READY STATUS RESTARTS AGE my-release-cockroachdb-0 1/1 Running 0 8m my-release-cockroachdb-1 1/1 Running 0 8m my-release-cockroachdb-2 1/1 Running 0 8m my-release-cockroachdb-init-hxzsc 0/1 Completed 0 1h ``` 2. Confirm that the persistent volumes and corresponding claims were created successfully for all three pods: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pv ``` ``` NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE pvc-71019b3a-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-0 standard 11m pvc-7108e172-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-1 standard 11m pvc-710dcb66-fc67-11e8-a606-080027ba45e5 100Gi RWO Delete Bound default/datadir-my-release-cockroachdb-2 standard 11m ``` The StatefulSet configuration sets all CockroachDB nodes to log to `stderr`, so if you ever need access to logs for a pod, use `kubectl logs ` rather than checking the log on the persistent volume. ## Step 3. Use the built-in SQL client 1. Launch a temporary interactive pod and start the [built-in SQL client](/docs/v26.4/cockroach-sql) inside it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach: \ --rm \ --restart=Never \ -- sql \ --insecure \ --host=cockroachdb-public ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl run cockroachdb -it \ --image=cockroachdb/cockroach: \ --rm \ --restart=Never \ -- sql \ --insecure \ --host=my-release-cockroachdb-public ``` 2. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE bank; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE bank.accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), balance DECIMAL ); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO bank.accounts (balance) VALUES (1000.50), (20000), (380), (500), (55000); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.accounts; ``` ``` id | balance +--------------------------------------+---------+ 6f123370-c48c-41ff-b384-2c185590af2b | 380 990c9148-1ea0-4861-9da7-fd0e65b0a7da | 1000.50 ac31c671-40bf-4a7b-8bee-452cff8a4026 | 500 d58afd93-5be9-42ba-b2e2-dc00dcedf409 | 20000 e6d8f696-87f5-4d3c-a377-8e152fdc27f7 | 55000 (5 rows) ``` 3. Exit the SQL shell and delete the temporary pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` ## Step 4. Access the DB Console To access the cluster's [DB Console](/docs/v26.4/ui-overview): 1. On secure clusters, [certain pages of the DB Console](/docs/v26.4/ui-overview#db-console-access) can only be accessed by `admin` users. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach/cockroach-certs \ --host=cockroachdb-public ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure \ -- ./cockroach sql \ --certs-dir=/cockroach-certs \ --host=cockroachdb-public ``` \$ kubectl exec -it cockroachdb-client-secure \ \-- ./cockroach sql \ \--certs-dir=/cockroach-certs \ \--host=my-release-cockroachdb-public 2. Assign `roach` to the `admin` role (you only need to do this once): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > GRANT admin TO roach; ``` 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` 4. In a new terminal window, port-forward from your local machine to the `cockroachdb-public` service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward service/cockroachdb-public 8080 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward service/cockroachdb-public 8080 ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward service/my-release-cockroachdb-public 8080 ``` ``` Forwarding from 127.0.0.1:8080 -> 8080 ``` 5. Go to [https://localhost:8080](https://localhost:8080) and log in with the username and password you created earlier. If you are using Google Chrome, and you are getting an error about not being able to reach `localhost` because its certificate has been revoked, go to chrome://flags/#allow-insecure-localhost, enable "Allow invalid certificates for resources loaded from localhost", and then restart the browser. Enabling this Chrome feature degrades security for all sites running on `localhost`, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily. 1. Go to [http://localhost:8080](http://localhost:8080). 2. In the UI, verify that the cluster is running as expected: * View the [Node List](/docs/v26.4/ui-cluster-overview-page#node-list) to ensure that all nodes successfully joined the cluster. * Click the **Databases** tab on the left to verify that `bank` is listed. ## Step 5. Simulate node failure Based on the `replicas: 3` line in the StatefulSet configuration, Kubernetes ensures that three pods/nodes are running at all times. When a pod/node fails, Kubernetes automatically creates another pod/node with the same network identity and persistent storage. To see this in action: 1. Terminate one of the CockroachDB nodes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod cockroachdb-2 ``` ``` pod "cockroachdb-2" deleted ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod cockroachdb-2 ``` ``` pod "cockroachdb-2" deleted ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod my-release-cockroachdb-2 ``` ``` pod "my-release-cockroachdb-2" deleted ``` 2. In the DB Console, the **Cluster Overview** will soon show one node as **Suspect**. As Kubernetes auto-restarts the node, watch how the node once again becomes healthy. 3. Back in the terminal, verify that the pod was automatically restarted: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pod cockroachdb-2 ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-2 1/1 Running 0 12s ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pod cockroachdb-2 ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-2 1/1 Running 0 12s ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pod my-release-cockroachdb-2 ``` ``` NAME READY STATUS RESTARTS AGE my-release-cockroachdb-2 1/1 Running 0 44s ``` ## Step 6. Stop the cluster This procedure shuts down the CockroachDB cluster and deletes the resources you just created, including the logs. This command intentionally does **not** delete the persistent volumes that were attached to the pods or any secrets you may have created. Before deleting a cluster's persistent volumes, be sure to back them up. For more information, refer to [Delete a Cluster's Persistent Volumes](#delete-a-cluster’s-persistent-volumes) and [Managing Secrets Using `kubectl`](https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl) in the Kubernetes project's documentation. > [!CAUTION] > > Do **not** use the `--all` flag to `kubectl delete`, to avoid the risk of unintentional data loss. This command is very long; you may need to scroll your browser to read all of it. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete \ pods,statefulsets,services,poddisruptionbudget,jobs,rolebinding,clusterrolebinding,role,clusterrole,serviceaccount,alertmanager,prometheus,prometheusrule,serviceMonitor \ -l app=cockroachdb ``` ``` pod "cockroachdb-0" deleted pod "cockroachdb-1" deleted pod "cockroachdb-2" deleted pod "cockroachdb-3" deleted service "alertmanager-cockroachdb" deleted service "cockroachdb" deleted service "cockroachdb-public" deleted poddisruptionbudget "cockroachdb-budget" deleted job "cluster-init" deleted clusterrolebinding "prometheus" deleted clusterrole "prometheus" deleted serviceaccount "prometheus" deleted alertmanager "cockroachdb" deleted prometheus "cockroachdb" deleted prometheusrule "prometheus-cockroachdb-rules" deleted servicemonitor "cockroachdb" deleted ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ helm uninstall my-release ``` ``` release "my-release" deleted ``` ### Delete a cluster's persistent volumes If you need to free up the storage used by CockroachDB, you can optionally delete the persistent volumes that were attached to the pods, after first backing up your data. > [!CAUTION] > > Before you delete a cluster's persistent volumes, be sure you have a backup copy of your data. Data **cannot** be recovered once the persistent volumes are deleted. For more information, see the [Kubernetes documentation](https://kubernetes.io/docs/tasks/run-application/delete-stateful-set/#persistent-volumes). Refer to the Kubernetes project's documentation for more information and recommendations. ### Stop Kubernetes To delete the Kubernetes cluster: * Hosted GKE: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters delete cockroachdb ``` * Hosted EKS: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl delete cluster --name cockroachdb ``` * Manual GCE: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cluster/kube-down.sh ``` * Manual AWS: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cluster/kube-down.sh ``` ## See also * [Kubernetes Overview](/docs/v26.4/kubernetes-overview) * [Deploy CockroachDB on Kubernetes](/docs/v26.4/deploy-cockroachdb-with-kubernetes) * [Cluster monitoring](/docs/v26.4/monitor-cockroachdb-kubernetes) * [Kubernetes Multi-Cluster Deployment](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster) * [Kubernetes Performance Guide](/docs/v26.4/kubernetes-performance) * [Production Checklist](/docs/v26.4/recommended-production-settings) # Deploy CockroachDB on Red Hat OpenShift Source: https://docs.cockroachlabs.com/docs/stable/deploy-cockroachdb-with-kubernetes-openshift This page shows you how to start and stop a secure 3-node CockroachDB cluster on the Red Hat OpenShift platform, using the [Public operator](https://catalog.redhat.com/software/containers/cockroachdb/cockroachdb-operator/5d9cbed3ecb5240ff271264f). > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). ## Before you begin You must have the following set up before proceeding with this tutorial: * A running OpenShift cluster > [!NOTE] > > This article assumes you have already installed the OpenShift Container Platform as your Kubernetes cluster. For details on this, see the [OpenShift documentation](https://docs.openshift.com/container-platform/). ## Step 1. Create a CockroachDB namespace 1. Create a `cockroachdb` namespace. You will create the CockroachDB cluster in this namespace: > [!NOTE] > > `oc` runs `kubectl` commands on OpenShift clusters, using the same syntax. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc create namespace cockroachdb ``` ``` namespace/cockroachdb created ``` 1. Set `cockroachdb` as the default namespace: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc config set-context --current --namespace=cockroachdb ``` ``` Context "admin" modified. ``` Validate that this was successful: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc config view --minify | grep namespace: ``` ``` namespace: cockroachdb ``` This lets you issue `oc` commands without having to specify the namespace each time. ## Step 2. Install the public operator 1. Navigate to your OpenShift web console and click **OperatorHub**. 2. Enter "cockroach" in the search box. There are two tiles called **CockroachDB Operator**. Find the tile *without* the `Marketplace` label (which requires a subscription). ![OpenShift OperatorHub](https://mintcdn.com/cockroachlabs/Vnu3Mn2DzHS7Vfry/images/common/cockroachdb-operator-openshift.png?fit=max\&auto=format\&n=Vnu3Mn2DzHS7Vfry\&q=85\&s=962d7c59d72790ea523a3a3740a85e33) Click the **CockroachDB Operator** tile and then **Install**. 3. On the **Install Operator** page, select `cockroachdb` in the **Installed Namespace** dropdown and click **Install**. 4. Confirm that the operator is running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ oc get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroach-operator-65c4f6df45-h5r5n 1/1 Running 0 51s ``` ## Step 3. Start CockroachDB 1. When the operator is ready, click **View Operator** to navigate to the **Installed Operators** page. 2. In the **CockroachDB Operator** tile, click **Create instance**. ![OpenShift OperatorHub](https://mintcdn.com/cockroachlabs/Vnu3Mn2DzHS7Vfry/images/common/cockroachdb-operator-instance-openshift.png?fit=max\&auto=format\&n=Vnu3Mn2DzHS7Vfry\&q=85\&s=df18095725e7c64ad23e8b26c8ddb7ea) 3. Make sure **CockroachDB Version** is set to a valid CockroachDB version. For a list of compatible image names, see `spec.containers.env` in the [pulic operator manifest](https://raw.github.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml) on GitHub. 4. This will open the **Create CrdbCluster** page. By default, this deploys a 3-node secure cluster. Leave the other fields unchanged and click **Create**. 5. Navigate to **Workloads** > **Pods** and observe the pods being created: ![OpenShift OperatorHub](https://mintcdn.com/cockroachlabs/Vnu3Mn2DzHS7Vfry/images/common/cockroachdb-operator-pods-openshift.png?fit=max\&auto=format\&n=Vnu3Mn2DzHS7Vfry\&q=85\&s=0773dbdd003862ac197d48ec2ed389a4) 6. You can also use the command line to view the pods: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroach-operator-65c4f6df45-h5r5n 1/1 Running 0 6m11s crdb-tls-example-0 1/1 Running 0 3m15s crdb-tls-example-1 1/1 Running 0 103s crdb-tls-example-2 1/1 Running 0 89s ``` ## Step 4. Create a secure client pod To use the CockroachDB SQL client, first launch a secure pod running the `cockroach` binary. This can be defined with the following YAML, which mounts the operator's generated certificates: > [!TIP] > > `spec.containers.image` should match the **Image** value that is displayed under the **Containers** section on the **Pods** page when you select a CockroachDB pod. Be sure to select a CockroachDB pod and not the operator pod. > > Note that OpenShift may display the image SHA instead of the tag. In this case, you should use the SHA for `spec.containers.image`. ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: v1 kind: Pod metadata: name: crdb-client-secure labels: app.kubernetes.io/component: database app.kubernetes.io/instance: crdb-tls-example app.kubernetes.io/name: cockroachdb spec: serviceAccountName: cockroach-operator-sa containers: - name: crdb-client-secure image: registry.connect.redhat.com/cockroachdb/cockroach:v20.2.8 imagePullPolicy: IfNotPresent volumeMounts: - name: client-certs mountPath: /cockroach/cockroach-certs/ command: - sleep - "2147483648" # 2^31 terminationGracePeriodSeconds: 0 volumes: - name: client-certs projected: sources: - secret: name: crdb-tls-example-node items: - key: ca.crt path: ca.crt - secret: name: crdb-tls-example-root items: - key: tls.crt path: client.root.crt - key: tls.key path: client.root.key defaultMode: 256 ``` 1. On the **Pods** page, click **Create Pod** and replace the existing YAML with the above manifest. 2. Click **Create**. Return to the **Pods** page and check that the client pod `crdb-client-secure` is running. This is also visible on the command-line: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc get pods ``` ``` NAME READY STATUS RESTARTS AGE cockroach-operator-65c4f6df45-h5r5n 1/1 Running 0 6m11s crdb-client-secure 1/1 Running 0 14m crdb-tls-example-0 1/1 Running 0 3m15s crdb-tls-example-1 1/1 Running 0 103s crdb-tls-example-2 1/1 Running 0 89s ``` ## Step 5. Use the CockroachDB SQL client 1. Start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql) from the client pod: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc exec -it crdb-client-secure -- ./cockroach sql --certs-dir=/cockroach/cockroach-certs/ --host=crdb-tls-example-public ``` ``` # # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. # # Server version: CockroachDB CCL v20.2.8 (x86_64-unknown-linux-gnu, built 2021/04/23 13:54:57, go1.13.14) (same version as client) # Cluster ID: 0813c343-c86b-4be8-9ad0-477cdb5db749 # # Enter \? for a brief introduction. # root@crdb-tls-example-public:26257/defaultdb> ``` Now you can run SQL commands against the cluster. 2. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE bank; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO bank.accounts VALUES (1, 1000.50); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.accounts; ``` ``` id | balance +----+---------+ 1 | 1000.50 (1 row) ``` 3. [Create a user with a password](/docs/v26.4/create-user#create-a-user-with-a-password): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS'; ``` You will need this username and password to access the DB Console later. 4. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` **Note:** If you cannot access the SQL client, this may be related to your `--certs-dir` or `--host` flags. 1. Shell into the client pod and check for the necessary certs in the `--certs-dir` directory: > [!TIP] > > You can also access the client pod by selecting it on the **Pods** page and clicking **Terminal**. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc exec -it crdb-client-secure sh ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # cd /cockroach/cockroach-certs # ls ``` ``` ca.crt client.root.key client.root.crt ``` 1. Check the name of the `public` service to use with the `--host` flag: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc get services ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE crdb-tls-example ClusterIP None 26257/TCP,8080/TCP 14m crdb-tls-example-public ClusterIP 172.25.180.197 26257/TCP,8080/TCP 14m ``` ## Step 6. Access the DB Console To access the CockroachDB cluster's [DB Console](/docs/v26.4/ui-overview): 1. On secure clusters, [certain pages of the DB Console](/docs/v26.4/ui-overview#db-console-access) can only be accessed by `admin` users. Start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql) from the client pod: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc exec -it crdb-client-secure -- ./cockroach sql --certs-dir=/cockroach/cockroach-certs/ --host=crdb-tls-example-public ``` 2. Assign `roach` to the `admin` role (you only need to do this once): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > GRANT admin TO roach; ``` 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` 4. In a new terminal window, port-forward from your local machine to the `crdb-tls-example-public` service: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc port-forward service/crdb-tls-example-public 8080 ``` ``` Forwarding from [::1]:8080 -> 8080 ``` 5. Go to [https://localhost:8080](https://localhost:8080) and log in with the username and password you created earlier. > [!NOTE] > > If you are using Google Chrome, and you are getting an error about not being able to reach `localhost` because its certificate has been revoked, go to chrome://flags/#allow-insecure-localhost, enable "Allow invalid certificates for resources loaded from localhost", and then restart the browser. Enabling this Chrome feature degrades security for all sites running on `localhost`, not just CockroachDB's DB Console, so be sure to enable the feature only temporarily. ## Step 7. Run a sample workload To run a sample [CockroachDB workload](/docs/v26.4/cockroach-workload): 1. Use the secure client pod to load the `movr` schema on one of the CockroachDB pods: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc exec -it crdb-client-secure -- ./cockroach workload init movr 'postgresql://root@crdb-tls-example-0.crdb-tls-example.cockroachdb:26257?sslcert=%2Fcockroach%2Fcockroach-certs%2Fclient.root.crt&sslkey=%2Fcockroach%2Fcockroach-certs%2Fclient.root.key&sslmode=verify-full&sslrootcert=%2Fcockroach%2Fcockroach-certs%2Fca.crt' ``` 2. Initialize and run the workload for 3 minutes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} oc exec -it crdb-client-secure -- ./cockroach workload run movr --duration=3m --tolerate-errors --max-rate=20 --concurrency=1 --display-every=10s 'postgresql://root@crdb-tls-example-0.crdb-tls-example.cockroachdb:26257?sslcert=%2Fcockroach%2Fcockroach-certs%2Fclient.root.crt&sslkey=%2Fcockroach%2Fcockroach-certs%2Fclient.root.key&sslmode=verify-full&sslrootcert=%2Fcockroach%2Fcockroach-certs%2Fca.crt' ``` 3. Select one of the CockroachDB pods on the **Pods** page and click **Logs**. This will reveal the JDBC URL that your application can use to connect to CockroachDB: ![OpenShift OperatorHub](https://mintcdn.com/cockroachlabs/Vnu3Mn2DzHS7Vfry/images/common/cockroachdb-operator-logs-openshift.png?fit=max\&auto=format\&n=Vnu3Mn2DzHS7Vfry\&q=85\&s=4a80dad3cd0b8866d1069d5bb6d244ed) ## Step 8. Delete the cluster > [!NOTE] > > If you want to continue using this cluster, see the documentation on [configuring](/docs/v26.4/configure-cockroachdb-kubernetes), [scaling](/docs/v26.4/scale-cockroachdb-kubernetes), [monitoring](/docs/v26.4/monitor-cockroachdb-kubernetes), and [upgrading](/docs/v26.4/upgrade-cockroachdb-kubernetes) the cluster. 1. Go to the **Installed Operators** page and find the cluster name of the CockroachDB cluster. Select **Delete CrdbCluster** from the menu. ![OpenShift OperatorHub](https://mintcdn.com/cockroachlabs/Vnu3Mn2DzHS7Vfry/images/common/cockroachdb-operator-delete-openshift.png?fit=max\&auto=format\&n=Vnu3Mn2DzHS7Vfry\&q=85\&s=bac317398f6bba9546c09ef42ef02d86) This will delete the CockroachDB cluster being run by the operator. It will *not* delete: * The persistent volumes that were attached to the pods. This can be done by deleting the PVCs via **Storage** > **Persistent Volume Claims**. * The opaque secrets used to authenticate the cluster. This can be done via **Workloads** > **Secrets**. > [!CAUTION] > > If you want to delete the persistent volumes and free up the storage used by CockroachDB, be sure you have a backup copy of your data. Data **cannot** be recovered once the persistent volumes are deleted. For more information, see the [Kubernetes documentation](https://kubernetes.io/docs/tasks/run-application/delete-stateful-set/#persistent-volumes). > [!NOTE] > > For more information on managing secrets, see the [Kubernetes documentation](https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl). # Deployment & Operations Skills Taxonomy Source: https://docs.cockroachlabs.com/docs/stable/deployment-operations-skills-taxonomy This document outlines the foundational skills required to deploy and operate CockroachDB in production environments. The skills are organized into sections based on the following operational domains: * [Infrastructure configuration](#infrastructure-configuration) * [Security](#security) * [Cluster maintenance](#cluster-maintenance) * [Troubleshooting](#troubleshooting) * [Disaster recovery](#disaster-recovery) Each section includes links to relevant documentation for the listed skills. > [!TIP] > > Cockroach Labs offers [Professional Services](https://www.cockroachlabs.com/company/professional-services/) that can assist you with getting applications into production faster and more efficiently. ## Infrastructure configuration This section covers how to ensure that your hardware and network are properly configured to meet the performance and connectivity requirements of CockroachDB. * [Verify vCPU, RAM, storage, and disk IOPS performance](/docs/v26.4/recommended-production-settings#hardware) * [Configure time synchronization with NTP server](/docs/v26.4/deploy-cockroachdb-on-premises#step-1-synchronize-clocks) * [Validate network connectivity](/docs/v26.4/cluster-setup-troubleshooting#tcp-connection-lingering) ## Security This section covers how to secure a CockroachDB deployment, including certificate management, load balancing setup, role-based access control, and data encryption. * [Create and distribute certificates; initialize cluster](/docs/v26.4/deploy-cockroachdb-on-premises#step-2-generate-certificates) * [Configure load balancer and direct a workload](/docs/v26.4/deploy-cockroachdb-on-premises#step-6-set-up-load-balancing) * [Configure RBAC](/docs/v26.4/security-reference/authorization) * [Encryption at rest](/docs/v26.4/encryption) ## Cluster maintenance This section covers how to manage the lifecycle of CockroachDB nodes, including adding and removing nodes, handling outages, performing upgrades or downgrades, and modifying cluster settings. * [Shut down a node gracefully](/docs/v26.4/node-shutdown) * [Handle unplanned node outages](/docs/v26.4/recommended-production-settings#load-balancing) * [Add nodes](/docs/v26.4/cockroach-start#add-a-node-to-a-cluster) * [Remove nodes](/docs/v26.4/node-shutdown?filters=decommission#remove-nodes) * [Add a region](/docs/v26.4/alter-database#add-regions-to-a-database) * [Remove a region](/docs/v26.4/alter-database#drop-region) * [Rolling upgrades](/docs/v26.4/upgrade-cockroach-version#perform-a-patch-upgrade) * Downgrade a cluster from a [patch version](/docs/v26.4/upgrade-cockroach-version#roll-back-a-patch-upgrade) * Downgrade a cluster from a [major version](/docs/v26.4/upgrade-cockroach-version#roll-back-a-major-version-upgrade) * [Change a cluster setting](/docs/v26.4/cluster-settings#change-a-cluster-setting) * Repave a cluster: cluster repaving involves the following individual skills, which are also used during [rolling upgrades](/docs/v26.4/upgrade-cockroach-version#perform-a-patch-upgrade): 1. [Shut down a node gracefully](/docs/v26.4/node-shutdown) 2. Detach the [persistent volume](/docs/v26.4/kubernetes-overview#kubernetes-terminology) (a.k.a. persistent disk) from the removed node's virtual machine (VM) (this step is optional but recommended) 3. Delete the removed node's VM 4. Start a new VM 5. Reattach the persistent disk to the new VM (necessary if you did step #2) 6. [Add a node to the cluster](/docs/v26.4/cockroach-start#add-a-node-to-a-cluster) from the new VM ## Troubleshooting This section contains a list of common issues related to SQL performance, cluster stability, memory usage, load balancing, and changefeed lag. * [SQL response time for specific queries](/docs/v26.4/query-behavior-troubleshooting#query-issues) * [SQL throughput degradation across the board](/docs/v26.4/query-behavior-troubleshooting#low-throughput) * [Cluster instability: Dead/suspect nodes](/docs/v26.4/cluster-setup-troubleshooting#node-liveness-issues) * [Out of memory (OOM) problems](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash) * [Imbalanced cluster load](/docs/v26.4/architecture/replication-layer#load-based-replica-rebalancing) * [End of file (EOF) errors](/docs/v26.4/cluster-setup-troubleshooting#client-connection-issues) * [Changefeed is falling behind](/docs/v26.4/advanced-changefeed-configuration#lagging-ranges) * [Gather diagnostic data from a "debug zip" file](/docs/v26.4/cockroach-debug-zip) * [Collect timeseries diagnostic data from a "tsdump" file](/docs/v26.4/cockroach-debug-tsdump) ## Disaster recovery This section covers how to set up and manage backup and restore of your cluster to ensure data recovery in case of failures. * [Create AWS IAM access key](/docs/v26.4/cloud-storage-authentication) * [Create S3 bucket for backup data](/docs/v26.4/use-cloud-storage#amazon-s3-storage-classes) * [Full cluster backup to S3](/docs/v26.4/take-full-and-incremental-backups#full-backups) * [Incremental backup to S3](/docs/v26.4/take-full-and-incremental-backups#incremental-backups) * [Cluster restore from AWS S3](/docs/v26.4/restore#restore-a-cluster) ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Deploy a Local Cluster from Binary (Secure)](/docs/v26.4/secure-a-cluster) * [SQL Performance Best Practices](/docs/v26.4/performance-best-practices-overview) * [Performance Tuning Recipes](/docs/v26.4/performance-recipes) * [Troubleshoot Self-Hosted Setup](/docs/v26.4/cluster-setup-troubleshooting) # Disaster Recovery Overview Source: https://docs.cockroachlabs.com/docs/stable/disaster-recovery-overview Resilient deployments aim for continuity in database operations to protect from data loss and downtime. CockroachDB's built-in [Raft replication](/docs/v26.4/architecture/replication-layer) and [fault tolerance](/docs/v26.4/demo-cockroachdb-resilience) provide high availability. However, it is still important to design a *disaster recovery* plan to recover from unforeseen incidents to minimize downtime and data loss. As you evaluate CockroachDB's disaster recovery features, consider your organization's requirements for the amount of tolerable data loss and the acceptable length of time to recover. * **Recovery Point Objective (RPO)**: The maximum amount of data loss (measured by time) that an organization can tolerate. * **Recovery Time Objective (RTO)**: The maximum length of time it should take to restore normal operations following an outage. When you use backups, RPO and RTO can be visualized as follows: ![Simulating RPO and RTO. With RPO representing the tolerable data loss, and RTO representing the tolerable time to recovery.](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/rpo-rto.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=a351ee446a3997d921dd8ef95db6ad17) > [!NOTE] > > For an overview of resiliency features in CockroachDB, refer to [Data Resilience](/docs/v26.4/data-resilience). ## Choose a disaster recovery strategy CockroachDB is designed to recover automatically; however, building [backups](/docs/v26.4/backup-and-restore-overview) or [physical cluster replication](/docs/v26.4/physical-cluster-replication-overview) into your disaster recovery planning protects against unforeseen incidents. | | Point-in-time backup & restore | Physical cluster replication (asynchronous) | | - | - | - | | **RPO** | >=5 minutes | 10s of seconds | | **RTO** | Minutes to hours, depending on data size and number of nodes | Seconds to minutes, depending on cluster size, and time of failover | | **Write latency** | No impact | No impact | | **Recovery** | Manual restore | Manual failover | | **Fault tolerance** | Not applicable | Zero RPO node, availability zone within a cluster, region failures with loss up to RPO in a two-region (or two-datacenter) setup | | **Minimum regions to achieve fault tolerance** | 1 | 2 | ## See also * [Set Up Physical Cluster Replication](/docs/v26.4/set-up-physical-cluster-replication) * [Physical Cluster Replication Technical Overview](/docs/v26.4/physical-cluster-replication-technical-overview) * [Backup Architecture](/docs/v26.4/backup-architecture) * [Backup and Restore Overview](/docs/v26.4/backup-and-restore-overview) * [Managed Backups](/docs/cockroachcloud/managed-backups) # CockroachDB Docs MCP Server Source: https://docs.cockroachlabs.com/docs/stable/docs-mcp-integration The CockroachDB Docs MCP Server ([Model Context Protocol](https://modelcontextprotocol.io/introduction)) enables AI assistants like Claude Desktop, Cursor, and VS Code to access CockroachDB documentation directly. Self-hosted customers can also integrate the server into custom agents and automation workflows using an [authenticated endpoint](#authenticated-endpoint-for-automation). ## Setup Connect your AI assistant to CockroachDB documentation by configuring the MCP server. The following sections describe platform-specific instructions. ### Cursor 1. Create or open the file `.cursor/mcp.json` in your project directory. 2. Add the following configuration: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "mcpServers": { "cockroachdb-docs": { "type": "http", "url": "https://cockroachdb.mcp.kapa.ai" } } } ``` 3. Restart Cursor to apply the configuration. 4. You can now ask questions about CockroachDB documentation directly in Cursor. ### VS Code > [!NOTE] > > Requires VS Code 1.102 or later with GitHub Copilot. 1. Create or open the file `.vscode/mcp.json` in your project directory. 2. Add the following configuration: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "servers": { "cockroachdb-docs": { "type": "http", "url": "https://cockroachdb.mcp.kapa.ai" } } } ``` 3. Reload VS Code window (⌘+R). 4. The CockroachDB documentation is now available through GitHub Copilot in VS Code. ### Claude Code 1. Run the following command in your terminal: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} claude mcp add --transport http cockroachdb-docs https://cockroachdb.mcp.kapa.ai ``` 2. Execute `/mcp` in Claude Code and authenticate via browser when prompted. CockroachDB documentation is now accessible in your Claude Code environment. ### ChatGPT Desktop 1. Open ChatGPT Desktop. 2. Go to **Settings** → **Features** and enable **Developer mode**. 3. Navigate to **Settings** → **MCP Servers**. 4. Click **Add Server** and enter: * **Name**: `cockroachdb-docs` * **URL**: `https://cockroachdb.mcp.kapa.ai` 5. CockroachDB documentation is now accessible in ChatGPT Desktop. ### Claude Desktop 1. Open Claude Desktop configuration file: * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` * **Linux**: `~/.config/Claude/claude_desktop_config.json` 2. Add the CockroachDB Docs MCP server to your configuration: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "mcpServers": { "cockroachdb-docs": { "type": "npx", "args": ["mcp-remote", "https://cockroachdb.mcp.kapa.ai"] } } } ``` 3. Save the file and restart Claude Desktop. 4. You can now query CockroachDB documentation directly in Claude Desktop. ### Other MCP clients For other MCP-compatible clients, use the following server configuration: **Server URL**: `https://cockroachdb.mcp.kapa.ai` **Generic configuration format**: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "mcpServers": { "cockroachdb-docs": { "url": "https://cockroachdb.mcp.kapa.ai" } } } ``` Consult your client's documentation for specific configuration instructions. ## Authenticated endpoint for automation For self-hosted CockroachDB customers who want to integrate the Docs MCP Server into custom agents or automation workflows, an authenticated endpoint is available. This endpoint requires your [CockroachDB license key](/docs/v26.4/licensing-faqs#obtain-a-license). > [!NOTE] > > The authenticated endpoint is currently available to self-hosted CockroachDB customers. ### Configuration Use the following endpoint with your [CockroachDB license key](/docs/v26.4/licensing-faqs#obtain-a-license): **Server URL**: `https://docs-mcp.cockroachlabs.com/mcp` **Generic configuration format**: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "mcpServers": { "cockroachdb-docs": { "url": "https://docs-mcp.cockroachlabs.com/mcp", "headers": { "Authorization": "Bearer {YOUR_LICENSE_KEY}" } } } } ``` Replace `\{YOUR_LICENSE_KEY\}` with your CockroachDB license key. ### Authentication errors (401) If you receive a `401 Unauthorized` error, check the following: 1. Verify your license key is correct. Refer to the [licensing FAQ](/docs/v26.4/licensing-faqs#obtain-a-license) for details on obtaining your key. 2. Check that the `Authorization` header is formatted as `Bearer \{YOUR_LICENSE_KEY\}` (note the space after `Bearer`). 3. Ensure your license has not expired. 4. If you recently received your license, it may take up to 24 hours to be activated in our system. ## Capabilities Once connected, your AI assistant can answer questions about CockroachDB directly from the official documentation. Example queries include: ### Multi-region configuration * "How do I set up a multi-region CockroachDB cluster?" * "What are the best practices for configuring region survival goals?" * "Show me how to implement follow-the-workload patterns" ### Performance optimization * "What are the recommended techniques for optimizing query performance?" * "How do I identify and resolve hot spots in my cluster?" * "Explain the best practices for index design in CockroachDB" ### Security features * "How do I configure TLS/SSL encryption for my cluster?" * "What are the steps to implement role-based access control?" * "Show me how to set up audit logging in CockroachDB" ### SQL syntax and features * "What's the syntax for creating a changefeed?" * "How do I use window functions in CockroachDB?" * "Explain the differences between JSONB operators in CockroachDB" ### Troubleshooting * "How do I diagnose and fix connection refused errors?" * "What steps should I take when encountering transaction retry errors?" * "How do I investigate and resolve node liveness issues?" ### Operations and maintenance * "What's the recommended backup strategy for production clusters?" * "How do I perform a rolling upgrade of my cluster?" * "Show me the best practices for monitoring CockroachDB" ## Troubleshooting ### Connection issues If your AI assistant cannot connect to the CockroachDB documentation: 1. Verify your internet connection. 2. Check that the MCP server URL is correctly configured. 3. Restart your AI assistant application. 4. Ensure you have the latest version of your AI assistant. ### No results If queries return no results: 1. Try rephrasing your question to be more specific. 2. Include "CockroachDB" in your query for better context. 3. Check the [CockroachDB documentation](/docs) directly to verify the information exists. ### Configuration not working If the configuration doesn't seem to take effect: 1. Ensure the configuration file is saved in the correct location. 2. Check for JSON syntax errors in your configuration. 3. Fully quit and restart your application (not just reload). 4. For Claude Desktop: Verify that `npx` is available in your system `PATH`. ## Feedback and support For issues or feedback about the CockroachDB Docs MCP Server, join the [CockroachDB Community Slack](https://www.cockroachlabs.com/join-community). ## See also * [Model Context Protocol](https://modelcontextprotocol.io/) # Enable the Node Map Source: https://docs.cockroachlabs.com/docs/stable/enable-node-map The **Node Map** is useful for: * Visualizing the geographic configuration of a multi-region cluster on a world map. * Viewing real-time cluster metrics. * Drilling down to individual nodes for monitoring health and performance. This page guides you through the process of setting up and enabling the Node Map. ![DB Console](https://mintcdn.com/cockroachlabs/6M4oBmgCef68NEHr/images/common/ui-node-map-navigation3.png?fit=max\&auto=format\&n=6M4oBmgCef68NEHr\&q=85\&s=42c228cb140abd50d7f301b8ab53e19b) ## Set up and enable the Node Map To enable the Node Map, you need to start the cluster with the correct [`--locality`](/docs/v26.4/cockroach-start#locality) flags and assign the latitude and longitude for each locality. > [!NOTE] > > The Node Map will not be displayed until *all* nodes are started with the correct `--locality` flags and all localities are assigned the corresponding latitude and longitude. Consider a four-node geo-distributed cluster with the following configuration: | Node | Region | Datacenter | | - | - | - | | Node1 | us-east-1 | us-east-1a | | Node2 | us-east-1 | us-east-1b | | Node3 | us-west-1 | us-west-1a | | Node4 | eu-west-1 | eu-west-1a | ### Step 1. Start the nodes with the correct `--locality` flags To start a new cluster with the correct `--locality` flags: 1. Start Node 1: ``` $ cockroach start \ --insecure \ --locality=region=us-east-1,datacenter=us-east-1a \ --advertise-addr= [!NOTE] > > To be displayed on the world map, localities must be assigned a corresponding latitude and longitude. ### Step 3. Set the latitudes and longitudes for the localities 1. Launch the built-in SQL client: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach sql --insecure --host=
INSERT INTO system.locations VALUES ('region', 'us-east-1', 37.478397, -76.453077), ('region', 'us-west-1', 38.837522, -120.895824), ('region', 'eu-west-1', 53.142367, -7.692054); ``` For the latitudes and longitudes of AWS, Azure, and Google Cloud regions, see [Location Coordinates for Reference](#location-coordinates). ### Step 4. Refresh the Node Map Refresh the DB Console to see the updated Node Map: ![DB Console](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/ui-node-map-complete.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=9b028bff3014c2b997049349a9524a2f) ### Step 5. Navigate the Node Map To navigate to Node 2, which is in datacenter `us-east-1a` in the `us-east-1` region: 1. Click the map component marked as **region=us-east-1** on the Node Map. The [locality component](/docs/v26.4/ui-cluster-overview-page#locality-component) for the datacenter is displayed. ![DB Console](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/ui-node-map-navigation1.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=f314fb1110e30a1dfec4f71a0cbf27cd) 2. Click the datacenter component marked as **datacenter=us-east-1a**. The individual [node components](/docs/v26.4/ui-cluster-overview-page#node-component) are displayed. ![DB Console](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/ui-node-map-navigation2.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=41fa38aa628bc28d1e4e8bdf43f6d9dd) 3. To navigate back to the cluster view, either click **Cluster** in the breadcrumb trail at the top of the Node Map, or click **Up to REGION=US-EAST-1** and then click **Up to CLUSTER** in the lower left-hand side of the Node Map. ## Troubleshoot the Node Map ### Node Map not displayed * All nodes in the cluster must be assigned [localities](/docs/v26.4/cockroach-start#locality). * Localities must be [assigned a corresponding latitude and longitude](#step-3-set-the-latitudes-and-longitudes-for-the-localities). To verify all requirements, navigate to the [**Localities**](/docs/v26.4/ui-debug-pages#configuration) debug page in the DB Console. ![DB Console](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/ui-localities-debug.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=50ec25e8f0d59ac1ed60a90a33242a70) The **Localities** debug page displays the following: * Localities configuration that you set up while starting the nodes with the `--locality` flags. * Nodes corresponding to each locality. * Latitude and longitude coordinates for each locality. ### World Map not displayed for all locality levels The world map is displayed only when [localities are assigned latitude and longitude coordinates](#step-3-set-the-latitudes-and-longitudes-for-the-localities). If a locality (e.g., region) is not assigned latitude and longitude coordinates, it is displayed using the latitude and longitude of any lower-level localities it contains (e.g., datacenter). If no coordinates are available, localities are plotted in a circular layout. ### Displayed Used Capacity value is more than configured Capacity If you are testing your deployment locally with multiple CockroachDB nodes running on a single machine (this is [not recommended in production](/docs/v26.4/recommended-production-settings#topology)), you must explicitly [set the store size](/docs/v26.4/cockroach-start#store) per node in order to display the correct capacity. Otherwise, the machine's actual disk capacity will be counted as a separate store for each node, thus inflating the computed capacity. ## Location coordinates This section lists the latitudes and longitudes of AWS, Azure, and Google Cloud regions. ### AWS locations | Location | SQL Statement | | - | - | | US East (N. Virginia) | `INSERT into system.locations VALUES ('region', 'us-east-1', 37.478397, -76.453077)` | | US East (Ohio) | `INSERT into system.locations VALUES ('region', 'us-east-2', 40.417287, -76.453077)` | | US West (N. California) | `INSERT into system.locations VALUES ('region', 'us-west-1', 38.837522, -120.895824)` | | US West (Oregon) | `INSERT into system.locations VALUES ('region', 'us-west-2', 43.804133, -120.554201)` | | Canada (Central) | `INSERT into system.locations VALUES ('region', 'ca-central-1', 56.130366, -106.346771)` | | EU (Frankfurt) | `INSERT into system.locations VALUES ('region', 'eu-central-1', 50.110922, 8.682127)` | | EU (Ireland) | `INSERT into system.locations VALUES ('region', 'eu-west-1', 53.142367, -7.692054)` | | EU (London) | `INSERT into system.locations VALUES ('region', 'eu-west-2', 51.507351, -0.127758)` | | EU (Paris) | `INSERT into system.locations VALUES ('region', 'eu-west-3', 48.856614, 2.352222)` | | Asia Pacific (Tokyo) | `INSERT into system.locations VALUES ('region', 'ap-northeast-1', 35.689487, 139.691706)` | | Asia Pacific (Seoul) | `INSERT into system.locations VALUES ('region', 'ap-northeast-2', 37.566535, 126.977969)` | | Asia Pacific (Osaka-Local) | `INSERT into system.locations VALUES ('region', 'ap-northeast-3', 34.693738, 135.502165)` | | Asia Pacific (Singapore) | `INSERT into system.locations VALUES ('region', 'ap-southeast-1', 1.352083, 103.819836)` | | Asia Pacific (Sydney) | `INSERT into system.locations VALUES ('region', 'ap-southeast-2', -33.86882, 151.209296)` | | Asia Pacific (Mumbai) | `INSERT into system.locations VALUES ('region', 'ap-south-1', 19.075984, 72.877656)` | | South America (São Paulo) | `INSERT into system.locations VALUES ('region', 'sa-east-1', -23.55052, -46.633309)` | ### Azure locations | Location | SQL Statement | | - | - | | eastasia (East Asia) | `INSERT into system.locations VALUES ('region', 'eastasia', 22.267, 114.188)` | | southeastasia (Southeast Asia) | `INSERT into system.locations VALUES ('region', 'southeastasia', 1.283, 103.833)` | | centralus (Central US) | `INSERT into system.locations VALUES ('region', 'centralus', 41.5908, -93.6208)` | | eastus (East US) | `INSERT into system.locations VALUES ('region', 'eastus', 37.3719, -79.8164)` | | eastus2 (East US 2) | `INSERT into system.locations VALUES ('region', 'eastus2', 36.6681, -78.3889)` | | westus (West US) | `INSERT into system.locations VALUES ('region', 'westus', 37.783, -122.417)` | | northcentralus (North Central US) | `INSERT into system.locations VALUES ('region', 'northcentralus', 41.8819, -87.6278)` | | southcentralus (South Central US) | `INSERT into system.locations VALUES ('region', 'southcentralus', 29.4167, -98.5)` | | northeurope (North Europe) | `INSERT into system.locations VALUES ('region', 'northeurope', 53.3478, -6.2597)` | | westeurope (West Europe) | `INSERT into system.locations VALUES ('region', 'westeurope', 52.3667, 4.9)` | | japanwest (Japan West) | `INSERT into system.locations VALUES ('region', 'japanwest', 34.6939, 135.5022)` | | japaneast (Japan East) | `INSERT into system.locations VALUES ('region', 'japaneast', 35.68, 139.77)` | | australiaeast (Australia East) | `INSERT into system.locations VALUES ('region', 'australiaeast', -33.86, 151.2094)` | | australiasoutheast (Australia Southeast) | `INSERT into system.locations VALUES ('region', 'australiasoutheast', -37.8136, 144.9631)` | | southindia (South India) | `INSERT into system.locations VALUES ('region', 'southindia', 12.9822, 80.1636)` | | centralindia (Central India) | `INSERT into system.locations VALUES ('region', 'centralindia', 18.5822, 73.9197)` | | westindia (West India) | `INSERT into system.locations VALUES ('region', 'westindia', 19.088, 72.868)` | | canadacentral (Canada Central) | `INSERT into system.locations VALUES ('region', 'canadacentral', 43.653, -79.383)` | | canadaeast (Canada East) | `INSERT into system.locations VALUES ('region', 'canadaeast', 46.817, -71.217)` | | uksouth (UK South) | `INSERT into system.locations VALUES ('region', 'uksouth', 50.941, -0.799)` | | ukwest (UK West) | `INSERT into system.locations VALUES ('region', 'ukwest', 53.427, -3.084)` | | westcentralus (West Central US) | `INSERT into system.locations VALUES ('region', 'westcentralus', 40.890, -110.234)` | | westus2 (West US 2) | `INSERT into system.locations VALUES ('region', 'westus2', 47.233, -119.852)` | | koreacentral (Korea Central) | `INSERT into system.locations VALUES ('region', 'koreacentral', 37.5665, 126.9780)` | | koreasouth (Korea South) | `INSERT into system.locations VALUES ('region', 'koreasouth', 35.1796, 129.0756)` | | francecentral (France Central) | `INSERT into system.locations VALUES ('region', 'francecentral', 46.3772, 2.3730)` | | francesouth (France South) | `INSERT into system.locations VALUES ('region', 'francesouth', 43.8345, 2.1972)` | ### Google Cloud locations | Location | SQL Statement | | - | - | | us-east1 (South Carolina) | `INSERT into system.locations VALUES ('region', 'us-east1', 33.836082, -81.163727)` | | us-east4 (N. Virginia) | `INSERT into system.locations VALUES ('region', 'us-east4', 37.478397, -76.453077)` | | us-central1 (Iowa) | `INSERT into system.locations VALUES ('region', 'us-central1', 42.032974, -93.581543)` | | us-west1 (Oregon) | `INSERT into system.locations VALUES ('region', 'us-west1', 43.804133, -120.554201)` | | northamerica-northeast1 (Montreal) | `INSERT into system.locations VALUES ('region', 'northamerica-northeast1', 56.130366, -106.346771)` | | europe-west1 (Belgium) | `INSERT into system.locations VALUES ('region', 'europe-west1', 50.44816, 3.81886)` | | europe-west2 (London) | `INSERT into system.locations VALUES ('region', 'europe-west2', 51.507351, -0.127758)` | | europe-west3 (Frankfurt) | `INSERT into system.locations VALUES ('region', 'europe-west3', 50.110922, 8.682127)` | | europe-west4 (Netherlands) | `INSERT into system.locations VALUES ('region', 'europe-west4', 53.4386, 6.8355)` | | europe-west6 (Zürich) | `INSERT into system.locations VALUES ('region', 'europe-west6', 47.3769, 8.5417)` | | asia-east1 (Taiwan) | `INSERT into system.locations VALUES ('region', 'asia-east1', 24.0717, 120.5624)` | | asia-northeast1 (Tokyo) | `INSERT into system.locations VALUES ('region', 'asia-northeast1', 35.689487, 139.691706)` | | asia-southeast1 (Singapore) | `INSERT into system.locations VALUES ('region', 'asia-southeast1', 1.352083, 103.819836)` | | australia-southeast1 (Sydney) | `INSERT into system.locations VALUES ('region', 'australia-southeast1', -33.86882, 151.209296)` | | asia-south1 (Mumbai) | `INSERT into system.locations VALUES ('region', 'asia-south1', 19.075984, 72.877656)` | | southamerica-east1 (São Paulo) | `INSERT into system.locations VALUES ('region', 'southamerica-east1', -23.55052, -46.633309)` | # Manage Encryption for CockroachDB Self-Hosted Clusters Source: https://docs.cockroachlabs.com/docs/stable/encryption This page outlines several procedures necessary for managing encryption in CockroachDB clusters. ## Generating store key files Cockroach determines which encryption algorithm to use based on the size of the key file. The key file must contain random data making up the key ID (32 bytes) and the actual key (16, 24, or 32 bytes depending on the encryption algorithm). Review the recommendations for [Encryption at Rest](/docs/v26.4/security-reference/encryption) when deciding which algorithm to use. | Algorithm | Key size | Key file size | | - | - | - | | AES-128 | 128 bits (16 bytes) | 48 bytes | | AES-192 | 192 bits (24 bytes) | 56 bytes | | AES-256 | 256 bits (32 bytes) | 64 bytes | Generating a key file can be done using the `cockroach` CLI: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach gen encryption-key -s 128 /path/to/my/aes-128.key ``` Or the equivalent [openssl](https://www.openssl.org/docs/man1.1.1/man1/openssl.html) CLI command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ openssl rand -out /path/to/my/aes-128.key 48 ``` ## Starting a node with encryption Encryption at Rest is configured at node start time using the `--enterprise-encryption` command line flag. The flag specifies the encryption options for one of the stores on the node. If multiple stores exist, the flag must be specified for each store. The flag takes the form: `--enterprise-encryption=path= [!CAUTION] > > Once specified for a given store, the `--enterprise-encryption` flag must always be present. ## Checking encryption status Encryption status can be seen on the node's stores report, reachable through: `http(s)://nodeaddress:8080/#/reports/stores/local` (or replace `local` with the node ID). For example, if you are running a [local cluster](/docs/v26.4/secure-a-cluster), you can see the node's stores report at `https://localhost:8080/#/reports/stores/local`. The report shows encryption status for all stores on the selected node, including: * Encryption algorithm. * Active store key information. * Active data key information. * The fraction of files/bytes encrypted using the active data key. CockroachDB relies on [storage layer compactions](/docs/v26.4/architecture/storage-layer#compaction) to write new files using the latest encryption key. It may take several days for all files to be replaced. Some files are only rewritten at startup, and some keep older copies around, requiring multiple restarts. You can force storage compaction with the `cockroach debug compact` command (the node must first be [stopped](/docs/v26.4/node-shutdown#perform-node-shutdown)). The fraction of files/bytes encrypted on the store may be less than 100% for the following reasons: * The percentage shown is the percentage encrypted with the **current** data key, which rotates at the configured [`rotation-period`](#starting-a-node-with-encryption). When a data key rotates, the percentage will drop down to zero and slowly climb up as data is compacted. * In some cases, it may never reach 100%. This can happen because from the point in time at which encryption is enabled, CockroachDB only encrypts **new** data written to the filesystem. Because it relies entirely on storage layer compactions, there's no mechanism by which dormant on-disk data is encrypted. Information about keys is written to [the logs](/docs/v26.4/logging-overview), including: * Active/old key information at startup. * New key information after data key rotation. Alternatively, you can use the [`cockroach debug encryption-active-key`](/docs/v26.4/cockroach-debug-encryption-active-key) command to view information about a store's encryption algorithm and store key. ## Changing encryption algorithm or keys Encryption type and keys can be changed at any time by restarting the node. To change keys or encryption type, the `key` component of the `--enterprise-encryption` flag is set to the new key, while the key previously used must be specified in the `old-key` component. For example, we can switch from AES-128 to AES-256 using: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start --store=cockroach-data --enterprise-encryption=path=cockroach-data,key=/path/to/my/aes-256.key,old-key=/path/to/my/aes-128.key ``` Upon starting, the node will read the existing data keys using the old encryption key (`aes-128.key`), then rewrite the data keys using the new key (`aes-256.key`). A new data key will be generated to match the desired AES-256 algorithm. To check that the new key is active, use the stores report page in the DB Console to [check the encryption status](#checking-encryption-status). To disable encryption, specify `key=plain`. The data keys will be stored in plaintext and new data will not be encrypted. To rotate keys, specify `key=/path/to/my/new-aes-128.key` and `old-key=/path/to/my/old-aes-128.key`. The data keys will be decrypted using the old key and then encrypted using the new key. A new data key will also be generated. ## See also * [Column Level Encryption](/docs/v26.4/column-level-encryption) * [Cryptographic functions](/docs/v26.4/functions-and-operators#cryptographic-functions) # Essential Alerts for CockroachDB Self-Hosted Deployments Source: https://docs.cockroachlabs.com/docs/stable/essential-alerts-self-hosted ## Platform ### High CPU A node with a high CPU utilization, an *overloaded* node, has a limited ability to process the user workload and increases the risks of cluster instability. **Metric** \ [`sys.cpu.combined.percent-normalized`](/docs/v26.4/essential-metrics-self-hosted) \ [`sys.cpu.host.combined.percent-normalized`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node for each of the listed metrics: \ WARNING: Metric greater than `0.80` for `4 hours` \ CRITICAL: Metric greater than `0.90` for `1 hour` **Action** * Refer to [CPU Usage](/docs/v26.4/common-issues-to-monitor#cpu-usage) and [Workload Concurrency](/docs/v26.4/common-issues-to-monitor#workload-concurrency). * In the DB Console, navigate to **Metrics**, [**Hardware** dashboard](/docs/v26.4/ui-hardware-dashboard) for the cluster and check for high values on the [**CPU Percent** graph](/docs/v26.4/ui-hardware-dashboard#cpu-percent) and the [**Host CPU Percent** graph](/docs/v26.4/ui-hardware-dashboard#host-cpu-percent). * In the DB Console, navigate to **Metrics**, [**SQL** dashboard](/docs/v26.4/ui-sql-dashboard) for the cluster and check for high values on the [**Active SQL Statements** graph](/docs/v26.4/ui-sql-dashboard#active-sql-statements). This graph shows the true concurrency of the workload, which may exceed the cluster capacity planning guidance of no more than 4 active statements per vCPU or core. * A persistently high CPU utilization of all nodes in a CockroachDB cluster suggests the current compute resources may be insufficient to support the user workload's concurrency requirements. If confirmed, the number of processors (vCPUs or cores) in the CockroachDB cluster needs to be adjusted to sustain the required level of workload concurrency. For a prompt resolution, either add cluster nodes or throttle the workload concurrency, for example, by reducing the number of concurrent connections to not exceed 4 active statements per vCPU or core. ### Hot node (hotspot) Unbalanced utilization of CockroachDB nodes in a cluster may negatively affect the cluster's performance and stability, with some nodes getting overloaded while others remain relatively underutilized. **Metric** \ [`sys.cpu.combined.percent-normalized`](/docs/v26.4/essential-metrics-self-hosted) \ [`sys.cpu.host.combined.percent-normalized`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each of the listed metrics: \ WARNING: The max CPU utilization across all nodes exceeds the cluster's median CPU utilization by `30` for `2 hours` **Action** * Refer to [Understand hotspots](/docs/v26.4/understand-hotspots). ### Node memory utilization One node with high memory utilization is a cluster stability risk. High memory utilization is a prelude to a node's [out-of-memory (OOM) crash](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash) — the process is terminated by the OS when the system is critically low on memory. An OOM condition is not expected to occur if a CockroachDB cluster is provisioned and sized per [Cockroach Labs guidance](/docs/v26.4/common-issues-to-monitor#memory-planning). **Metric** \ [`sys.rss`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node: \ WARNING: `sys.rss` greater than `0.80` for `4 hours` \ CRITICAL: `sys.rss` greater than `0.90` for `1 hour` **Action** * Provision all CockroachDB VMs or machines with [sufficient RAM](/docs/v26.4/recommended-production-settings#memory). ### Node storage performance Under-configured or under-provisioned disk storage is a common root cause of inconsistent CockroachDB cluster performance and could also lead to cluster instability. Refer to [Disk IOPS](/docs/v26.4/common-issues-to-monitor#disk-iops). **Metric** \ [`sys.host.disk.iopsinprogress`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `sys.host.disk.iopsinprogress` greater than `10` for `10 seconds` \ CRITICAL: `sys.host.disk.iopsinprogress` greater than `20` for `10 seconds` **Action** * Provision enough storage capacity for CockroachDB data, and configure your volumes to maximize disk I/O. Refer to [Storage and disk I/O](/docs/v26.4/common-issues-to-monitor). ### Version mismatch All CockroachDB cluster nodes should be running the same exact executable (with identical build label). This warning guards against an operational error where some nodes were not upgraded. **Metric** \ `build.timestamp` **Rule** \ Set alerts for each node: \ WARNING: `build.timestamp` not the same across cluster nodes for more than `4 hours` **Action** * Ensure all cluster nodes are running exactly the same CockroachDB version, including the patch release version number. ### High open file descriptor count Send an alert when a cluster is getting close to the open file descriptor limit. **Metric** \ `sys.fd.open` \ `sys.fd.softlimit` **Rule** \ Set alerts for each node: \ WARNING: `sys_fd_open` / `sys_fd_softlimit` greater than `0.8` for `10 minutes` **Action** * Refer to [File descriptors limit](/docs/v26.4/recommended-production-settings#file-descriptors-limit). ## Storage ### Node storage capacity A CockroachDB node will not able to operate if there is no free disk space on a CockroachDB [store](/docs/v26.4/cockroach-start#store) volume. **Metric** \ [`capacity`](/docs/v26.4/essential-metrics-self-hosted) \ [`capacity.available`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node: \ WARNING: `capacity.available`/`capacity` is less than `0.30` for `24 hours` \ CRITICAL: `capacity.available`/`capacity` is less than `0.10` for `1 hour` **Action** * Refer to [Storage Capacity](/docs/v26.4/common-issues-to-monitor#storage-capacity). * Increase the size of CockroachDB node storage capacity. CockroachDB storage volumes should not be utilized more than 60% (40% free space). * In a "disk full" situation, you may be able to get a node "unstuck" by removing the [automatically created emergency ballast file](/docs/v26.4/cluster-setup-troubleshooting#automatic-ballast-files). ### Write stalls A high `write-stalls` value means CockroachDB is unable to write to a disk in an acceptable time, resulting in CockroachDB facing a disk latency issue and not responding to writes. **Metric** \ [`storage.write-stalls`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node: \ WARNING: `storage.write-stalls` per minute is greater than or equal to `1` per minute \ CRITICAL: `storage.write-stalls` per second is greater than or equal to `1` per second **Action** * Refer to [Disk stalls](/docs/v26.4/cluster-setup-troubleshooting#disk-stalls). ## Health ### Node restarting too frequently Send an alert if a node has restarted more than once in the last 10 minutes. Calculate this using the number of times the `sys.uptime` metric was reset back to zero. **Metric** \ [`sys.uptime`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node: \ WARNING: `sys.uptime` resets greater than `1` in the last `10 minutes` **Action** * Refer to [Node process restarts](/docs/v26.4/common-issues-to-monitor#node-process-restarts). ### Node LSM storage health CockroachDB uses the [Pebble](/docs/v26.4/architecture/storage-layer#pebble) storage engine that uses a [Log-structured Merge-tree (LSM tree)](/docs/v26.4/architecture/storage-layer#log-structured-merge-trees) to manage data storage. The health of an LSM tree can be measured by the [*read amplification*](/docs/v26.4/architecture/storage-layer#inverted-lsms), which is the average number of [SST files](/docs/v26.4/architecture/storage-layer#log-structured-merge-trees) being checked per read operation. A value in the single digits is characteristic of a healthy LSM tree. A value in the double, triple, or quadruple digits suggests an [inverted LSM](/docs/v26.4/architecture/storage-layer#inverted-lsms). A node reporting a high read amplification is an indication of a problem on that node that is likely to affect the workload. **Metric** \ `rocksdb.read-amplification` **Rule** \ Set alerts for each node: \ WARNING: `rocksdb.read-amplification` greater than `50` for `1 hour` \ CRITICAL: `rocksdb.read-amplification` greater than `150` for `15 minutes` **Action** * Refer to [LSM Health](/docs/v26.4/common-issues-to-monitor#lsm-health). ## Expiration of license and certificates ### Enterprise license expiration Avoid [license](/docs/v26.4/licensing-faqs) expiration to avoid any disruption to feature access. **Metric** \ [`seconds.until.enterprise.license.expiry`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `seconds.until.enterprise.license.expiry` is greater than `0` and less than `1814400` seconds (3 weeks) \ CRITICAL: `seconds.until.enterprise.license.expiry` is greater than `0` and less than `259200` seconds (3 days) **Action** [Renew the enterprise license](/docs/v26.4/licensing-faqs#renew-an-expired-license). ### Security certificate expiration Avoid [security certificate](/docs/v26.4/cockroach-cert) expiration. **Metric** \ [`security.certificate.expiration.ca`](/docs/v26.4/essential-metrics-self-hosted) \ [`security.certificate.expiration.client-ca`](/docs/v26.4/essential-metrics-self-hosted) \ [`security.certificate.expiration.ui`](/docs/v26.4/essential-metrics-self-hosted) \ [`security.certificate.expiration.ui-ca`](/docs/v26.4/essential-metrics-self-hosted) \ [`security.certificate.expiration.node`](/docs/v26.4/essential-metrics-self-hosted) \ [`security.certificate.expiration.node-client`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each of the listed metrics: \ WARNING: Metric is greater than `0` and less than `1814400` seconds (3 weeks) until enterprise license expiration \ CRITICAL: Metric is greater than `0` and less than `259200` seconds (3 days) until enterprise license expiration **Action** [Rotate the expiring certificates](/docs/v26.4/rotate-certificates). ## KV distributed During [rolling maintenance](/docs/v26.4/upgrade-cockroach-version) or planned cluster resizing, the nodes' state and count will be changing. **Mute KV distributed alerts described in the following sections during routine maintenance procedures** to avoid unnecessary distractions. ### Heartbeat latency Monitor the cluster health for early signs of instability. If this metric exceeds 1 second, it is a sign of instability. **Metric** \ [`liveness.heartbeatlatency`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `liveness.heartbeatlatency` greater than `0.5s` \ CRITICAL: `liveness.heartbeatlatency` greater than `3s` **Action** * Refer to [Node liveness issues](/docs/v26.4/cluster-setup-troubleshooting#node-liveness-issues). ### Live node count change The liveness checks reported by a node is inconsistent with the rest of the cluster. Number of live nodes in the cluster (will be 0 if this node is not itself live). This is a critical metric that tracks the live nodes in the cluster. **Metric** \ [`liveness.livenodes`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node: \ WARNING: max(`liveness.livenodes`) for the cluster - min(`liveness.livenodes`) for node > `0` for `2 minutes` \ CRITICAL: max(`liveness.livenodes`) for the cluster - min(`liveness.livenodes`) for node > `0` for `5 minutes` **Action** * Refer to [Node liveness issues](/docs/v26.4/cluster-setup-troubleshooting#node-liveness-issues). ### Intent buildup Send an alert when very large transactions are [locking](/docs/v26.4/architecture/transaction-layer#write-intents) millions of keys (rows). A common example is a transaction with a [`DELETE`](/docs/v26.4/delete) that affects a large number of rows. Transactions with an excessively large scope are often inadvertent, perhaps due to a non-selective filter and a specific data distribution that was not anticipated by an application developer. Transactions that create a large number of [write intents](/docs/v26.4/architecture/transaction-layer#write-intents) could have a negative effect on the workload's performance. These transactions may create locking contention, thus limiting concurrency. This would reduce throughput, and in extreme cases, lead to stalled workloads. **Metric** \ `intentcount` **Rule** \ WARNING: `intentcount` greater than 10,000,000 for 2 minutes \ CRITICAL: `intentcount` greater than 10,000,000 for 5 minutes \ For tighter transaction scope scrutiny, lower the `intentcount` threshold that triggers an alert. **Action** * Identify the large scope transactions that acquire a lot of locks. Consider reducing the scope of large transactions, implementing them as several smaller scope transactions. For example, if the alert is triggered by a large scope `DELETE`, consider "paging" `DELETE`s that target thousands of records instead of millions. This is often the most effective resolution, however it generally means an application level [refactoring](/docs/v26.4/bulk-update-data). * After reviewing the workload, you may conclude that a possible performance impact of allowing transactions to take a large number of intents is not a concern. For example, a large delete of obsolete, not-in-use data may create no concurrency implications and the elapsed time to execute that transaction may not be impactful. In that case, no response could be a valid way to handle this alert. ## KV replication ### Unavailable ranges Send an alert when the number of ranges with fewer live replicas than needed for quorum is non-zero for too long. **Metric** \ [`ranges.unavailable`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `ranges.unavailable` greater than `0` for `10 minutes` **Action** * Refer to [Replication issues](/docs/v26.4/cluster-setup-troubleshooting#replication-issues). ### Tripped replica circuit breakers Send an alert when a replica stops serving traffic due to other replicas being offline for too long. **Metric** \ `kv.replica_circuit_breaker.num_tripped_replicas` **Rule** \ WARNING: `kv.replica_circuit_breaker.num_tripped_replicas` greater than `0` for `10 minutes` **Action** * Refer to [Per-replica circuit breakers](/docs/v26.4/architecture/replication-layer#per-replica-circuit-breakers) and [Replication issues](/docs/v26.4/cluster-setup-troubleshooting#replication-issues). ### Under-replicated ranges Send an alert when the number of ranges with replication below the replication factor is non-zero for too long. **Metric** \ [`ranges.underreplicated`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `ranges.underreplicated` greater than `0` for `1 hour` **Action** * Refer to [Replication issues](/docs/v26.4/cluster-setup-troubleshooting#replication-issues). ### Requests stuck in Raft Send an alert when requests are taking a very long time in replication. An (evaluated) request has to pass through the replication layer, notably the quota pool and raft. If it fails to do so within a highly permissive duration, the gauge is incremented (and decremented again once the request is either applied or returns an error). A nonzero value indicates range or replica unavailability, and should be investigated. This can also be a symptom of a [leader-leaseholder split](/docs/v26.4/architecture/replication-layer). **Metric** \ `requests.slow.raft` **Rule** \ WARNING: `requests.slow.raft` greater than `0` for `10 minutes` **Action** * Refer to [Raft](/docs/v26.4/architecture/replication-layer#raft) and [Replication issues](/docs/v26.4/cluster-setup-troubleshooting#replication-issues). ## SQL ### Node not executing SQL Send an alert when a node is not executing SQL despite having connections. `sql.conns` shows the number of connections as well as the distribution, or balancing, of connections across cluster nodes. An imbalance can lead to nodes becoming overloaded. **Metric** \ [`sql.conns`](/docs/v26.4/essential-metrics-self-hosted) \ `sql.query.count` **Rule** \ Set alerts for each node: \ WARNING: `sql.conns` greater than `0` while `sql.query.count` equals `0` **Action** * Refer to [Connection Pooling](/docs/v26.4/connection-pooling). ### SQL query failure Send an alert when the query failure count exceeds a user-determined threshold based on their application's SLA. **Metric** \ [`sql.failure.count`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `sql.failure.count` is greater than a threshold (based on the user’s application SLA) **Action** * Use the [**Insights** page](/docs/v26.4/ui-insights-page) to find failed executions with their error code to troubleshoot or use application-level logs, if instrumented, to determine the cause of error. ### SQL queries experiencing high latency Send an alert when the query latency exceeds a user-determined threshold based on their application’s SLA. **Metric** \ [`sql.service.latency`](/docs/v26.4/essential-metrics-self-hosted) \ [`sql.conn.latency`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: (p99 or p90 of `sql.service.latency` plus average of `sql.conn.latency`) is greater than a threshold (based on the user’s application SLA) **Action** * Apply the time range of the alert to the [**SQL Activity** pages](/docs/v26.4/monitoring-and-alerting#sql-activity-pages) to investigate. Use the [**Statements** page](/docs/v26.4/ui-statements-page) P90 Latency and P99 latency columns to correlate [statement fingerprints](/docs/v26.4/ui-statements-page#sql-statement-fingerprints) with this alert. ## Backup ### Backup failure While CockroachDB is a distributed product, there is always a need to ensure backups complete. **Metric** \ [`schedules.BACKUP.failed`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ Set alerts for each node: \ WARNING: `schedules.BACKUP.failed` is greater than `0` **Action** * Refer to [Backup and Restore Monitoring](/docs/v26.4/backup-and-restore-monitoring). ## Changefeeds During [rolling maintenance](/docs/v26.4/upgrade-cockroach-version), [changefeed jobs](/docs/v26.4/change-data-capture-overview) restart following node restarts. **Mute changefeed alerts described in the following sections during routine maintenance procedures** to avoid unnecessary distractions. ### Changefeed failure Changefeeds can suffer permanent failures (that the [jobs system](/docs/v26.4/monitor-and-debug-changefeeds) will not try to restart). Any increase in this metric counter should prompt investigative action. **Metric** \ [`changefeed.failures`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ CRITICAL:  If `changefeed.failures` is greater than `0` **Action** 1. If the alert is triggered during cluster maintenance, mute it. Otherwise start investigation with the following query: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT job_id, status, ((high_water_timestamp/1000000000)::INT::TIMESTAMP) - NOW() AS "changefeed latency", created, LEFT(description, 60), high_water_timestamp FROM crdb_internal.jobs WHERE job_type = 'CHANGEFEED' AND status IN ('running', 'paused', 'pause-requested') ORDER BY created DESC; ``` 2. If the cluster is not undergoing maintenance, check the health of [sink](/docs/v26.4/changefeed-sinks) endpoints. If the sink is [Kafka](/docs/v26.4/changefeed-sinks#kafka), check for sink connection errors such as `ERROR: connecting to kafka: path.to.cluster:port: kafka: client has run out of available brokers to talk to (Is your cluster reachable?)`. ### Frequent changefeed restarts Changefeeds automatically restart in case of transient errors. However too many restarts outside of a routine maintenance procedure may be due to a systemic condition and should be investigated. **Metric** \ [`changefeed.error_retries`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING:  If `changefeed.error_retries` is greater than `50` for more than `15 minutes` **Action** * Follow the action for a [changefeed failure](#changefeed-failure). ### Changefeed falling behind Changefeed has fallen behind. This is determined by the end-to-end lag between a committed change and that change applied at the destination. This can be due to cluster capacity or changefeed sink availability. **Metric** \ [`changefeed.commit_latency`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING:  `changefeed.commit_latency` is greater than `10 minutes` \ CRITICAL: `changefeed.commit_latency` is greater than `15 minutes` **Action** 1. In the DB Console, navigate to **Metrics**, [**Changefeeds** dashboard](/docs/v26.4/ui-cdc-dashboard) for the cluster and check the maximum values on the [**Commit Latency** graph](/docs/v26.4/ui-cdc-dashboard#commit-latency). Alternatively, individual changefeed latency can be verified by using the following SQL query: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT job_id, status, ((high_water_timestamp/1000000000)::INT::TIMESTAMP) - NOW() AS "changefeed latency", created, LEFT(description, 60), high_water_timestamp FROM crdb_internal.jobs WHERE job_type = 'CHANGEFEED' AND status IN ('running', 'paused', 'pause-requested') ORDER BY created DESC; ``` 2. Copy the `job_id` for the changefeed job with highest `changefeed latency` and pause the job: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} PAUSE JOB 681491311976841286; ``` 3. Check the status of the pause request by running the query from step 1. If the job status is `pause-requested`, check again in a few minutes. 4. After the job is `paused`, resume the job. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} RESUME JOB 681491311976841286; ``` 5. If the changefeed latency does not progress after these steps due to lack of cluster resources or availability of the changefeed sink, [contact Support](https://support.cockroachlabs.com). ### Changefeed has been paused a long time Changefeed jobs should not be paused for a long time because [the protected timestamp prevents garbage collection](/docs/v26.4/protect-changefeed-data). To protect against an operational error, this alert guards against an inadvertently forgotten pause. **Metric** \ [`jobs.changefeed.currently_paused`](/docs/v26.4/essential-metrics-self-hosted) **Rule** \ WARNING: `jobs.changefeed.currently_paused` is greater than `0` for more than `15 minutes` \ CRITICAL: `jobs.changefeed.currently_paused` is greater than `0` for more than `60 minutes` **Action** 1. Check the status of each changefeed using the following SQL query: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT job_id, status, ((high_water_timestamp/1000000000)::INT::TIMESTAMP) - NOW() AS "changefeed latency",created, LEFT(description, 60), high_water_timestamp FROM crdb_internal.jobs WHERE job_type = 'CHANGEFEED' AND status IN ('running', 'paused','pause-requested') ORDER BY created DESC; ``` 2. If all the changefeeds have status as `running`, one or more changefeeds may have run into an error and recovered. In the DB Console, navigate to **Metrics**, [**Changefeeds** dashboard](/docs/v26.4/ui-cdc-dashboard) for the cluster and check the [**Changefeed Restarts** graph](/docs/v26.4/ui-cdc-dashboard#changefeed-restarts). 3. Resume paused changefeed(s) with the `job_id` using: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} RESUME JOB 681491311976841286; ``` ### Changefeed experiencing high latency Send an alert when the maximum latency of any running changefeed exceeds a specified threshold, which is less than the [`gc.ttlseconds`](/docs/v26.4/configure-replication-zones#replication-zone-variables) variable set in the cluster. This alert ensures that the changefeed progresses faster than the garbage collection TTL, preventing a changefeed's protected timestamp from delaying garbage collection. **Metric** \ [`changefeed.checkpoint_progress`](/docs/v26.4/monitor-and-debug-changefeeds#metrics) **Rule** \ WARNING: (current time minus `changefeed.checkpoint_progress`) is greater than a threshold (that is less than `gc.ttlseconds` variable) **Action** * Refer to [Monitor and Debug Changefeeds](/docs/v26.4/monitor-and-debug-changefeeds#recommended-changefeed-metrics-to-track). ## See also * [Events to alert on](/docs/v26.4/monitoring-and-alerting#events-to-alert-on) * [Common Issues to Monitor](/docs/v26.4/common-issues-to-monitor) * [Essential Metrics for CockroachDB Self-Hosted Deployments](/docs/v26.4/essential-metrics-self-hosted) # Essential Metrics for CockroachDB Self-Hosted Deployments Source: https://docs.cockroachlabs.com/docs/stable/essential-metrics-self-hosted These essential CockroachDB metrics let you monitor your CockroachDB self-hosted cluster. Use them to build custom dashboards with the following tools: * [Grafana](monitor-cockroachdb-with-prometheus#step-5-visualize-metrics-in-grafana) * Datadog Integration: The [**Datadog Integration Metric Name**](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics) column lists the corresponding Datadog metric which requires the `cockroachdb.` prefix. The **Usage** column explains why each metric is important to visualize and how to make both practical and actionable use of the metric in a production deployment. ## Platform
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`sys.cpu.combined.percent-normalized``sys.cpu.combined.percent.normalized`Current user+system cpu percentage consumed by the CRDB process, normalized 0-1 by number of coresThis metric gives the CPU utilization percentage by the CockroachDB process. If it is equal to 1 (or 100%), then the CPU is overloaded. The CockroachDB process should not be running with over 80% utilization for extended periods of time (hours). This metric is used in the DB Console CPU Percent graph.
`sys.cpu.host.combined.percent-normalized``sys.cpu.host.combined.percent_normalized`Current user+system cpu percentage across the whole machine, normalized 0-1 by number of coresThis metric gives the CPU utilization percentage of the underlying server, virtual machine, or container hosting the CockroachDB process. It includes CPU usage from both CockroachDB and non-CockroachDB processes. It also accounts for time spent processing hardware (irq) and software (softirq) interrupts, as well as nice time, which represents low-priority user-mode activity. A value of 1 (or 100%) indicates that the CPU is overloaded. Avoid running the CockroachDB process in an environment where the CPU remains overloaded for extended periods (e.g. multiple hours). This metric appears in the DB Console on the Host CPU Percent graph.
`sys.cpu.sys.percent``sys.cpu.sys.percent`Current system cpu percentage consumed by the CRDB processThis metric gives the CPU usage percentage at the system (Linux kernel) level by the CockroachDB process only. This is similar to the Linux top command output. The metric value can be more than 1 (or 100%) on multi-core systems. It is best to combine user and system metrics.
`sys.cpu.user.percent``sys.cpu.user.percent`Current user cpu percentage consumed by the CRDB processThis metric gives the CPU usage percentage at the user level by the CockroachDB process only. This is similar to the Linux top command output. The metric value can be more than 1 (or 100%) on multi-core systems. It is best to combine user and system metrics.
`sys.host.disk.iopsinprogress``sys.host.disk.iopsinprogress`IO operations currently in progress on this host (as reported by the OS)This metric gives the average queue length of the storage device. It characterizes the storage device's performance capability. All I/O performance metrics are Linux counters and correspond to the avgqu-sz in the Linux iostat command output. You need to view the device queue graph in the context of the actual read/write IOPS and MBPS metrics that show the actual device utilization. If the device is not keeping up, the queue will grow. Values over 10 are bad. Values around 5 mean the device is working hard trying to keep up. For internal (on chassis) NVMe devices, the queue values are typically 0. For network connected devices, such as AWS EBS volumes, the normal operating range of values is 1 to 2. Spikes in values are OK. They indicate an I/O spike where the device fell behind and then caught up. End users may experience inconsistent response times, but there should be no cluster stability issues. If the queue is greater than 5 for an extended period of time and IOPS or MBPS are low, then the storage is most likely not provisioned per Cockroach Labs guidance. In AWS EBS, it is commonly an EBS type, such as gp2, not suitable as database primary storage. If I/O is low and the queue is low, the most likely scenario is that the CPU is lacking and not driving I/O. One such case is a cluster with nodes with only 2 vcpus which is not supported sizing for production deployments. There are quite a few background processes in the database that take CPU away from the workload, so the workload is just not getting the CPU. Review storage and disk I/O.
`sys.host.disk.read.bytes``sys.host.disk.read.bytes`Bytes read from all disks since this process started (as reported by the OS)This metric reports the effective storage device read throughput (MB/s) rate. To confirm that storage is sufficiently provisioned, assess the I/O performance rates (IOPS and MBPS) in the context of the sys.host.disk.iopsinprogress metric.
`sys.host.disk.read.count``sys.host.disk.read.count`Disk read operations across all disks since this process started (as reported by the OS)This metric reports the effective storage device read IOPS rate. To confirm that storage is sufficiently provisioned, assess the I/O performance rates (IOPS and MBPS) in the context of the sys.host.disk.iopsinprogress metric.
`sys.host.disk.write.bytes``sys.host.disk.write.bytes`Bytes written to all disks since this process started (as reported by the OS)This metric reports the effective storage device write throughput (MB/s) rate. To confirm that storage is sufficiently provisioned, assess the I/O performance rates (IOPS and MBPS) in the context of the sys.host.disk.iopsinprogress metric.
`sys.host.disk.write.count``sys.host.disk.write.count`Disk write operations across all disks since this process started (as reported by the OS)This metric reports the effective storage device write IOPS rate. To confirm that storage is sufficiently provisioned, assess the I/O performance rates (IOPS and MBPS) in the context of the sys.host.disk.iopsinprogress metric.
`sys.host.net.recv.bytes``sys.host.net.recv.bytes`Bytes received on all network interfaces since this process started (as reported by the OS)This metric gives the node's ingress/egress network transfer rates for flat sections which may indicate insufficiently provisioned networking or high error rates. CockroachDB is using a reliable TCP/IP protocol, so errors result in delivery retries that create a "slow network" effect.
`sys.host.net.send.bytes``sys.host.net.send.bytes`Bytes sent on all network interfaces since this process started (as reported by the OS)This metric gives the node's ingress/egress network transfer rates for flat sections which may indicate insufficiently provisioned networking or high error rates. CockroachDB is using a reliable TCP/IP protocol, so errors result in delivery retries that create a "slow network" effect.
`sys.rss``sys.rss`Current process RSSThis metric gives the amount of RAM used by the CockroachDB process. Persistently low values over an extended period of time suggest there is underutilized memory that can be put to work with adjusted settings for --cache or --max_sql_memory or both. Conversely, a high utilization, even if a temporary spike, indicates an increased risk of Out-of-memory (OOM) crash (particularly since the swap is generally disabled).
`sys.runnable.goroutines.per.cpu``sys.runnable.goroutines.per.cpu`Average number of goroutines that are waiting to run, normalized by number of coresIf this metric has a value over 30, it indicates a CPU overload. If the condition lasts a short period of time (a few seconds), the database users are likely to experience inconsistent response times. If the condition persists for an extended period of time (tens of seconds, or minutes) the cluster may start developing stability issues. Review CPU planning.
`sys.uptime``sys.uptime`Process uptimeThis metric measures the length of time, in seconds, that the CockroachDB process has been running. Monitor this metric to detect events such as node restarts, which may require investigation or intervention.
## Storage
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`admission.io.overload``admission.io.overload`1-normalized float indicating whether IO admission control considers the store as overloaded with respect to compaction out of L0 (considers sub-level and file counts).If the value of this metric exceeds 1, then it indicates overload. You can also look at the metrics 'storage.l0-num-files', 'storage.l0-sublevels' or 'rocksdb.read-amplification' directly. A healthy LSM shape is defined as "read-amp \< 20" and "L0-files \< 1000", looking at cluster settings 'admission.l0_sub_level_count_overload_threshold' and 'admission.l0_file_count_overload_threshold' respectively.
`capacity``capacity.total`Total storage capacityThis metric gives total storage capacity. Measurements should comply with the following rule: CockroachDB storage volumes should not be utilized more than 60% (40% free space).
`capacity.available``capacity.available`Available storage capacityThis metric gives available storage capacity. Measurements should comply with the following rule: CockroachDB storage volumes should not be utilized more than 60% (40% free space).
`capacity.used``capacity.used`Used storage capacityThis metric gives used storage capacity. Measurements should comply with the following rule: CockroachDB storage volumes should not be utilized more than 60% (40% free space).
`rocksdb.block.cache.hits``rocksdb.block.cache.hits`Count of block cache hitsThis metric gives hits to block cache which is reserved memory. It is allocated upon the start of a node process by the '--cache' flag and never shrinks. By observing block cache hits and misses, you can fine-tune memory allocations in the node process for the demands of the workload.
`rocksdb.block.cache.misses``rocksdb.block.cache.misses`Count of block cache missesThis metric gives misses to block cache which is reserved memory. It is allocated upon the start of a node process by the '--cache' flag and never shrinks. By observing block cache hits and misses, you can fine-tune memory allocations in the node process for the demands of the workload.
`rocksdb.compactions``rocksdb.compactions`Number of table compactionsThis metric reports the number of a node's LSM compactions. If the number of compactions remains elevated while the LSM health does not improve, compactions are not keeping up with the workload. If the condition persists for an extended period, the cluster will initially exhibit performance issues that will eventually escalate into stability issues.
`storage.wal.failover.write_and_sync.latency`NOT AVAILABLEThe observed latency for writing and syncing to the logical Write-Ahead Log.Only populated when WAL failover is configured. Without WAL failover, the relevant metric is storage.wal.fsync.latency.
`storage.wal.fsync.latency``storage.wal.fsync.latency.count`The fsync latency to the Write-Ahead Log device.If this value is greater than 100ms, it is an indication of a disk stall. To mitigate the effects of disk stalls, consider deploying your cluster with WAL failover configured. When WAL failover is configured, the more relevant metric is storage.wal.failover_write_and_sync.latency, as this metric reflects the fsync latency of the primary and/or the secondary WAL device.
`storage.write-stalls``storage.write.stalls`Number of instances of intentional write stalls to backpressure incoming writesThis metric reports actual disk stall events. Ideally, investigate all reports of disk stalls. As a pratical guideline, one stall per minute is not likely to have a material impact on workload beyond an occasional increase in response time. However one stall per second should be viewed as problematic and investigated actively. It is particularly problematic if the rate persists over an extended period of time, and worse, if it is increasing.
## Health
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`admission.elastic_cpu.nanos_exhausted_duration``admission.elastic_cpu.nanos_exhausted_duration`Total duration when elastic CPU tokens (tokens measured in nanoseconds) were exhausted, as observed by the token granter (not waiters). This is reported in nanoseconds from 26.1 onwards, and was microseconds before that.This metric indicates when elastic CPU tokens are exhausted. Extended periods of elastic CPU token exhaustion may indicate high CPU utilization affecting elastic workloads.
`admission.granter.elastic_io_tokens_exhausted_duration.kv`NOT AVAILABLETotal duration when Elastic IO tokens were exhausted, as observed by the token granter (not waiters). This is reported in nanoseconds from 26.1 onwards, and was microseconds before that.This metric indicates when elastic I/O tokens are exhausted. Extended periods of elastic token exhaustion may indicate I/O bandwidth saturation affecting elastic workloads.
`admission.granter.io_tokens_exhausted_duration.kv``admission.granter.io_tokens_exhausted_duration.kv.count`Total duration when IO tokens were exhausted, as observed by the token granter (not waiters). This is reported in nanoseconds from 26.1 onwards, and was microseconds before that.This metric indicates when I/O tokens are exhausted. Extended periods of token exhaustion may indicate I/O bandwidth saturation or high disk utilization requiring attention.
`admission.granter.slots_exhausted_duration.kv``admission.granter.slots_exhausted_duration.kv.count`Total duration when KV slots were exhausted, as observed by the slot granter (not waiters). This is reported in nanoseconds from 26.1 onwards, and was microseconds before that.This metric indicates when KV slots are exhausted. Extended periods of slot exhaustion may indicate insufficient slot allocation or high request concurrency requiring attention.
`admission.wait_durations.cpu`NOT AVAILABLEWait time durations for requests that waitedThis is a latency histogram of wait time in the admission control queue. Non-zero wait times are expected when the corresponding resource is saturated.
`admission.wait_durations.elastic-cpu``admission.wait_durations.elastic_cpu.count`Wait time durations for requests that waitedThis is a latency histogram of wait time in the admission control queue. Non-zero wait times are expected when the corresponding resource is saturated.
`admission.wait_durations.elastic-stores`NOT AVAILABLEWait time durations for requests that waitedThis is a latency histogram of wait time in the admission control queue. Non-zero wait times are expected when the corresponding resource is saturated.
`admission.wait_durations.kv``admission.wait_durations.kv.count`Wait time durations for requests that waitedThis is a latency histogram of wait time in the CPU utilization-based admission control queue. Non-zero wait times are expected when CPU is saturated.
`admission.wait_durations.kv-stores``admission.wait_durations.kv_stores.count`Wait time durations for requests that waitedThis is a latency histogram of wait time in the I/O utilization-based admission control queue. Non-zero wait times are expected when I/O is saturated.
`admission.wait_durations.sql-kv-response``admission.wait_durations.sql_kv_response.count`Wait time durations for requests that waitedThis is a latency histogram of wait time in the admission control queue. Non-zero wait times are expected when the corresponding resource is saturated.
`admission.wait_durations.sql-sql-response``admission.wait_durations.sql_sql_response.count`Wait time durations for requests that waitedThis is a latency histogram of wait time in the admission control queue. Non-zero wait times are expected when the corresponding resource is saturated.
`kvflowcontrol.eval_wait.elastic.duration`NOT AVAILABLELatency histogram for time elastic requests spent waiting for flow tokens to evaluateThis metric shows how long requests are waiting for flow tokens before evaluation. Extended wait times may indicate flow control token exhaustion or replication lag.
`kvflowcontrol.eval_wait.regular.duration`NOT AVAILABLELatency histogram for time regular requests spent waiting for flow tokens to evaluateThis metric shows how long requests are waiting for flow tokens before evaluation. Extended wait times may indicate flow control token exhaustion or replication lag.
`kvflowcontrol.send_queue.bytes`NOT AVAILABLEByte size of all raft entries queued for sending to followers, waiting on available elastic send tokensThis metric indicates the size of queued raft entries waiting for elastic send tokens. Large or growing queue sizes may indicate replication backlog or follower lag.
## Network
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`clock-offset.meannanos``clock.offset.meannanos`Mean clock offset with other nodesThis metric gives the node's clock skew. In a well-configured environment, the actual clock skew would be in the sub-millisecond range. A skew exceeding 5 ms is likely due to a NTP service mis-configuration. Reducing the actual clock skew reduces the probability of uncertainty related conflicts and corresponding retires which has a positive impact on workload performance. Conversely, a larger actual clock skew increases the probability of retries due to uncertainty conflicts, with potentially measurable adverse effects on workload performance.
`rpc.connection.avg_round_trip_latency``rpc.connection.avg_round_trip_latency`Sum of exponentially weighted moving average of round-trip latencies, as measured through a gRPC RPC. Since this metric is based on gRPC RPCs, it is affected by application-level processing delays and CPU overload effects. See rpc.connection.tcp_rtt for a metric that is obtained from the kernel's TCP stack. Dividing this Gauge by rpc.connection.healthy gives an approximation of average latency, but the top-level round-trip-latency histogram is more useful. Instead, users should consult the label families of this metric if they are available (which requires prometheus and the cluster setting 'server.child_metrics.enabled'); these provide per-peer moving averages. This metric does not track failed connection. A failed connection's contribution is reset to zero.This metric is helpful in understanding general network issues outside of CockroachDB that could be impacting the user’s workload.
`rpc.connection.failures``rpc.connection.failures.count`Counter of failed connections. This includes both the event in which a healthy connection terminates as well as unsuccessful reconnection attempts. Connections that are terminated as part of local node shutdown are excluded. Decommissioned peers are excluded.See Description.
`rpc.connection.healthy``rpc.connection.healthy`Gauge of current connections in a healthy state (i.e. bidirectionally connected and heartbeating)See Description.
`rpc.connection.healthy_nanos``rpc.connection.healthy_nanos`Gauge of nanoseconds of healthy connection time On the prometheus endpoint scraped with the cluster setting 'server.child_metrics.enabled' set, the constituent parts of this metric are available on a per-peer basis and one can read off for how long a given peer has been connectedThis can be useful for monitoring the stability and health of connections within your CockroachDB cluster.
`rpc.connection.heartbeats``rpc.connection.heartbeats.count`Counter of successful heartbeats.See Description.
`rpc.connection.tcp_rtt`NOT AVAILABLEKernel-level TCP round-trip time as measured by the Linux TCP stack. This metric reports the smoothed round-trip time (SRTT) as maintained by the kernel's TCP implementation. Unlike application-level RPC latency measurements, this reflects pure network latency and is less affected by CPU overload effects. This metric is only available on Linux.High TCP RTT values indicate network issues outside of CockroachDB that could be impacting the user's workload.
`rpc.connection.tcp_rtt_var`NOT AVAILABLEKernel-level TCP round-trip time variance as measured by the Linux TCP stack. This metric reports the smoothed round-trip time variance (RTTVAR) as maintained by the kernel's TCP implementation. This measures the stability of the connection latency. This metric is only available on Linux.High TCP RTT variance values indicate network stability issues outside of CockroachDB that could be impacting the user's workload.
`rpc.connection.unhealthy``rpc.connection.unhealthy`Gauge of current connections in an unhealthy state (not bidirectionally connected or heartbeating)If the value of this metric is greater than 0, this could indicate a network partition.
`rpc.connection.unhealthy_nanos``rpc.connection.unhealthy_nanos`Gauge of nanoseconds of unhealthy connection time. On the prometheus endpoint scraped with the cluster setting 'server.child_metrics.enabled' set, the constituent parts of this metric are available on a per-peer basis and one can read off for how long a given peer has been unreachableIf this duration is greater than 0, this could indicate how long a network partition has been occurring.
`sys.host.net.send.tcp.retrans_segs`NOT AVAILABLEThe number of TCP segments retransmitted across all network interfaces. This can indicate packet loss occurring in the network. However, it can also be caused by recipient nodes not consuming packets in a timely manner, or the local node overflowing its outgoing buffers, for example due to overload. Retransmissions also occur in the absence of problems, as modern TCP stacks err on the side of aggressively retransmitting segments. The linux tool 'ss -i' can show the Linux kernel's smoothed view of round-trip latency and variance on a per-connection basis. Additionally, 'netstat -s' shows all TCP counters maintained by the kernel.Phase changes, especially when occurring on groups of nodes, can indicate packet loss in the network or a slow consumer of packets. On slow consumers, the 'sys.host.net.rcvd.drop' metric may be elevated; on overloaded senders, it is worth checking the 'sys.host.net.send.drop' metric. Additionally, the 'sys.host.net.send.tcp.\*' may provide more insight into the specific type of retransmission.
## KV Distributed
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`distsender.errors.notleaseholder``distsender.errors.notleaseholder`Number of NotLeaseHolderErrors encountered from replica-addressed RPCsErrors of this type are normal during elastic cluster topology changes when leaseholders are actively rebalancing. They are automatically retried. However they may create occasional response time spikes. In that case, this metric may provide the explanation of the cause.
`distsender.rpc.sent.nextreplicaerror``distsender.rpc.sent.nextreplicaerror`Number of replica-addressed RPCs sent due to per-replica errorsRPC errors do not necessarily indicate a problem. This metric tracks remote procedure calls that return a status value other than "success". A non-success status of an RPC should not be misconstrued as a network transport issue. It is database code logic executed on another cluster node. The non-success status is a result of an orderly execution of an RPC that reports a specific logical condition.
## KV Replication
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`leases.transfers.success``leases.transfers.success`Number of successful lease transfersA high number of lease transfers is not a negative or positive signal, rather it is a reflection of the elastic cluster activities. For example, this metric is high during cluster topology changes. A high value is often the reason for NotLeaseHolderErrors which are normal and expected during rebalancing. Observing this metric may provide a confirmation of the cause of such errors.
`liveness.heartbeatlatency``liveness.heartbeatlatency`Node liveness heartbeat latencyIf this metric exceeds 1 second, it is a sign of cluster instability.
`liveness.livenodes``liveness.livenodes`Number of live nodes in the cluster (will be 0 if this node is not itself live)This is a critical metric that tracks the live nodes in the cluster.
`queue.replicate.replacedecommissioningreplica.error``queue.replicate.replacedecommissioningreplica.error.count`Number of failed decommissioning replica replacements processed by the replicate queueRefer to Decommission the node.
`range.merges``range.merges.count`Number of range mergesThis metric indicates how fast a workload is scaling down. Merges are Cockroach's optimization for performance. This metric indicates that there have been deletes in the workload.
`range.splits``range.splits.count`Number of range splitsThis metric indicates how fast a workload is scaling up. Spikes can indicate resource hotspots since the split heuristic is based on QPS. To understand whether hotspots are an issue and with which tables and indexes they are occurring, correlate this metric with other metrics such as CPU usage, such as sys.cpu.combined.percent-normalized, or use the Hot Ranges page.
`ranges``ranges`Number of rangesThis metric provides a measure of the scale of the data size.
`ranges.unavailable``ranges.unavailable`Number of ranges with fewer live replicas than needed for quorumThis metric is an indicator of replication issues. It shows whether the cluster is unhealthy and can impact workload. If an entire range is unavailable, then it will be unable to process queries.
`ranges.underreplicated``ranges.underreplicated`Number of ranges with fewer live replicas than the replication targetThis metric is an indicator of replication issues. It shows whether the cluster has data that is not conforming to resilience goals. The next step is to determine the corresponding database object, such as the table or index, of these under-replicated ranges and whether the under-replication is temporarily expected. Use the statement SELECT table_name, index_name FROM \[SHOW RANGES WITH INDEXES] WHERE range_id = \{id of under-replicated range};
`rebalancing.cpunanospersecond``rebalancing.cpunanospersecond`Average CPU nanoseconds spent on processing replica operations in the last 30 minutes.A high value of this metric could indicate that one of the store's replicas is part of a hot range.
`rebalancing.lease.transfers``rebalancing.lease.transfers.count`Number of lease transfers motivated by store-level load imbalancesUsed to identify when there has been more rebalancing activity triggered by imbalance between stores (of QPS or CPU). If this is high (when the count is rated), it indicates that more rebalancing activity is taking place due to load imbalance between stores.
`rebalancing.queriespersecond``rebalancing.queriespersecond`Number of kv-level requests received per second by the store, considering the last 30 minutes, as used in rebalancing decisions.This metric shows hotspots along the queries per second (QPS) dimension. It provides insights into the ongoing rebalancing activities.
`rebalancing.range.rebalances``rebalancing.range.rebalances.count`Number of range rebalance operations motivated by store-level load imbalancesUsed to identify when there has been more rebalancing activity triggered by imbalance between stores (of QPS or CPU). If this is high (when the count is rated), it indicates that more rebalancing activity is taking place due to load imbalance between stores.
`rebalancing.replicas.cpunanospersecond``rebalancing.replicas.cpunanospersecond.count`Histogram of average CPU nanoseconds spent on processing replica operations in the last 30 minutes.A high value of this metric could indicate that one of the store's replicas is part of a hot range. See also the non-histogram variant: rebalancing.cpunanospersecond.
`rebalancing.replicas.queriespersecond``rebalancing.replicas.queriespersecond.count`Histogram of average kv-level requests received per second by replicas on the store in the last 30 minutes.A high value of this metric could indicate that one of the store's replicas is part of a hot range. See also: rebalancing_replicas_cpunanospersecond.
`replicas``replicas`Number of replicasThis metric provides an essential characterization of the data distribution across cluster nodes.
`replicas.leaseholders``replicas.leaseholders`Number of lease holdersThis metric provides an essential characterization of the data processing points across cluster nodes.
## SQL
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`auth.cert.conn.latency`NOT AVAILABLELatency to establish and authenticate a SQL connection using certificateSee Description.
`auth.cert.san.conn.success`NOT AVAILABLENumber of successful SQL connections using SAN-based certificate authenticationThis metric tracks successful authentications when SAN-based certificate validation is enabled. Use this to monitor adoption and success rate of SAN authentication. Failure rate = auth.cert.san.conn.total - auth.cert.san.conn.success.
`auth.cert.san.conn.total`NOT AVAILABLETotal number of SQL connection attempts using SAN-based certificate authenticationThis metric tracks all authentication attempts when SAN-based certificate validation is enabled. Compare with auth.cert.san.conn.success to calculate failure rate.
`auth.gss.conn.latency`NOT AVAILABLELatency to establish and authenticate a SQL connection using GSSSee Description.
`auth.jwt.conn.latency`NOT AVAILABLELatency to establish and authenticate a SQL connection using JWT TokenSee Description.
`auth.ldap.conn.latency`NOT AVAILABLELatency to establish and authenticate a SQL connection using LDAPSee Description.
`auth.ldap.conn.latency.internal`NOT AVAILABLEInternal Auth Latency to establish and authenticate a SQL connection using LDAP(excludes external LDAP calls)See Description.
`auth.password.conn.latency`NOT AVAILABLELatency to establish and authenticate a SQL connection using passwordSee Description.
`auth.scram.conn.latency`NOT AVAILABLELatency to establish and authenticate a SQL connection using SCRAMSee Description.
`jobs.auto_create_partial_stats.currently_paused`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{name: auto_create_partial_stats, status: currently_paused}`NOT AVAILABLENumber of auto_create_partial_stats jobs currently considered PausedThis metric is a high-level indicator that automatically generated partial statistics jobs are paused which can lead to the query optimizer running with stale statistics. Stale statistics can cause suboptimal query plans to be selected leading to poor query performance.
`jobs.auto_create_partial_stats.currently_running`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{type: auto_create_partial_stats, status: currently_running}`NOT AVAILABLENumber of auto_create_partial_stats jobs currently running in Resume or OnFailOrCancel stateThis metric tracks the number of active automatically generated partial statistics jobs that could also be consuming resources. Ensure that foreground SQL traffic is not impacted by correlating this metric with SQL latency and query volume metrics.
`jobs.auto_create_partial_stats.resume_failed`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs.resume{name: auto_create_partial_stats, status: failed}`NOT AVAILABLENumber of auto_create_partial_stats jobs which failed with a non-retriable errorThis metric is a high-level indicator that automatically generated partial table statistics is failing. Failed statistic creation can lead to the query optimizer running with stale statistics. Stale statistics can cause suboptimal query plans to be selected leading to poor query performance.
`sql.conn.failures``sql.conn.failures.count`Number of SQL connection failuresThis metric is incremented whenever a connection attempt fails for any reason, including timeouts.
`sql.conn.latency``sql.conn.latency`Latency to establish and authenticate a SQL connectionThese metrics characterize the database connection latency which can affect the application performance, for example, by having slow startup times. Connection failures are not recorded in these metrics.
`sql.conns``sql.conns`Number of open SQL connectionsThis metric shows the number of connections as well as the distribution, or balancing, of connections across cluster nodes. An imbalance can lead to nodes becoming overloaded. Review Connection Pooling.
`sql.ddl.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: ddl}``sql.ddl.count`Number of SQL DDL statements successfully executedThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.delete.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: delete}``sql.delete.count`Number of SQL DELETE statements successfully executedThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.distsql.contended_queries.count``sql.distsql.contended_queries.count`Number of SQL queries that experienced contentionThis metric is incremented whenever there is a non-trivial amount of contention experienced by a statement whether read-write or write-write conflicts. Monitor this metric to correlate possible workload performance issues to contention conflicts.
`sql.failure.count``sql.failure.count`Number of statements resulting in a planning or runtime errorThis metric is a high-level indicator of workload and application degradation with query failures. Use the Insights page to find failed executions with their error code to troubleshoot or use application-level logs, if instrumented, to determine the cause of error.
`sql.full.scan.count``sql.full.scan.count`Number of full table or index scansThis metric is a high-level indicator of potentially suboptimal query plans in the workload that may require index tuning and maintenance. To identify the statements with a full table scan, use SHOW FULL TABLE SCAN or the SQL Activity Statements page with the corresponding metric time frame. The Statements page also includes explain plans and index recommendations. Not all full scans are necessarily bad especially over smaller tables.
`sql.insert.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: insert}``sql.insert.count`Number of SQL INSERT statements successfully executedThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.mem.root.current``sql.mem.root.current`Current sql statement memory usage for rootThis metric shows how memory set aside for temporary materializations, such as hash tables and intermediary result sets, is utilized. Use this metric to optimize memory allocations based on long term observations. The maximum amount is set with --max_sql_memory. If the utilization of sql memory is persistently low, perhaps some portion of this memory allocation can be shifted to --cache.
`sql.new_conns``sql.new_conns.count`Number of SQL connections createdThe rate of this metric shows how frequently new connections are being established. This can be useful in determining if a high rate of incoming new connections is causing additional load on the server due to a misconfigured application.
`sql.routine.delete.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: routine_delete}`NOT AVAILABLENumber of SQL DELETE statements successfully executed within routine invocationThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.routine.insert.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: routine_insert}`NOT AVAILABLENumber of SQL INSERT statements successfully executed within routine invocationThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.routine.select.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: routine_select}`NOT AVAILABLENumber of SQL SELECT statements successfully executed within routine invocationThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.routine.update.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: routine_update}`NOT AVAILABLENumber of SQL UPDATE statements successfully executed within routine invocationThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.select.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: select}``sql.select.count`Number of SQL SELECT statements successfully executedThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`sql.service.latency``sql.service.latency`Latency of SQL request executionThese high-level metrics reflect workload performance. Monitor these metrics to understand latency over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. The Statements page has P90 Latency and P99 latency columns to enable correlation with this metric.
`sql.statements.active``sql.statements.active`Number of currently active user SQL statementsThis high-level metric reflects workload volume.
`sql.txn.abort.count``sql.txn.abort.count`Number of SQL transaction abort errorsThis high-level metric reflects workload performance. A persistently high number of SQL transaction abort errors may negatively impact the workload performance and needs to be investigated.
`sql.txn.begin.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: begin}``sql.txn.begin.count`Number of SQL transaction BEGIN statements successfully executedThis metric reflects workload volume by counting explicit transactions. Use this metric to determine whether explicit transactions can be refactored as implicit transactions (individual statements).
`sql.txn.commit.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: commit}``sql.txn.commit.count`Number of SQL transaction COMMIT statements successfully executedThis metric shows the number of transactions that completed successfully. This metric can be used as a proxy to measure the number of successful explicit transactions.
`sql.txn.latency``sql.txn.latency`Latency of SQL transactionsThese high-level metrics provide a latency histogram of all executed SQL transactions. These metrics provide an overview of the current SQL workload.
`sql.txn.rollback.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: rollback}``sql.txn.rollback.count`Number of SQL transaction ROLLBACK statements successfully executedThis metric shows the number of orderly transaction rollbacks. A persistently high number of rollbacks may negatively impact the workload performance and needs to be investigated.
`sql.txns.open``sql.txns.open`Number of currently open user SQL transactionsThis metric should roughly correspond to the number of cores \* 4. If this metric is consistently larger, scale out the cluster.
`sql.update.count`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `sql.count{query_type: update}``sql.update.count`Number of SQL UPDATE statements successfully executedThis high-level metric reflects workload volume. Monitor this metric to identify abnormal application behavior or patterns over time. If abnormal patterns emerge, apply the metric's time range to the SQL Activity pages to investigate interesting outliers or patterns. For example, on the Transactions page and the Statements page, sort on the Execution Count column. To find problematic sessions, on the Sessions page, sort on the Transaction Count column. Find the sessions with high transaction counts and trace back to a user or application.
`txn.restarts.serializable``txn.restarts.serializable`Number of restarts due to a forwarded commit timestamp and isolation=SERIALIZABLEThis metric is one measure of the impact of contention conflicts on workload performance. For guidance on contention conflicts, review transaction contention best practices and performance tuning recipes. Tens of restarts per minute may be a high value, a signal of an elevated degree of contention in the workload, which should be investigated.
`txn.restarts.txnaborted``txn.restarts.txnaborted.count`Number of restarts due to an abort by a concurrent transaction (usually due to deadlock)The errors tracked by this metric are generally due to deadlocks. Deadlocks can often be prevented with a considered transaction design. Identify the conflicting transactions involved in the deadlocks, then, if possible, redesign the business logic implementation prone to deadlocks.
`txn.restarts.txnpush``txn.restarts.txnpush.count`Number of restarts due to a transaction push failureThis metric is one measure of the impact of contention conflicts on workload performance. For guidance on contention conflicts, review transaction contention best practices and performance tuning recipes. Tens of restarts per minute may be a high value, a signal of an elevated degree of contention in the workload, which should be investigated.
`txn.restarts.unknown``txn.restarts.unknown.count`Number of restarts due to a unknown reasonsThis metric is one measure of the impact of contention conflicts on workload performance. For guidance on contention conflicts, review transaction contention best practices and performance tuning recipes. Tens of restarts per minute may be a high value, a signal of an elevated degree of contention in the workload, which should be investigated.
`txn.restarts.writetooold``txn.restarts.writetooold`Number of restarts due to a concurrent writer committing firstThis metric is one measure of the impact of contention conflicts on workload performance. For guidance on contention conflicts, review transaction contention best practices and performance tuning recipes. Tens of restarts per minute may be a high value, a signal of an elevated degree of contention in the workload, which should be investigated.
`txnwaitqueue.deadlocks_total``txnwaitqueue.deadlocks_total.count`Number of deadlocks detected by the txn wait queueAlert on this metric if its value is greater than zero, especially if transaction throughput is lower than expected. Applications should be able to detect and recover from deadlock errors. However, transaction performance and throughput can be maximized if the application logic avoids deadlock conditions in the first place, for example, by keeping transactions as short as possible.
## Table Statistics
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`jobs.auto_create_stats.currently_paused`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{name: auto_create_stats, status: currently_paused}``jobs.auto_create_stats.currently_paused`Number of auto_create_stats jobs currently considered PausedThis metric is a high-level indicator that automatically generated statistics jobs are paused which can lead to the query optimizer running with stale statistics. Stale statistics can cause suboptimal query plans to be selected leading to poor query performance.
`jobs.auto_create_stats.currently_running`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{type: auto_create_stats, status: currently_running}``jobs.auto_create_stats.currently_running`Number of auto_create_stats jobs currently running in Resume or OnFailOrCancel stateThis metric tracks the number of active automatically generated statistics jobs that could also be consuming resources. Ensure that foreground SQL traffic is not impacted by correlating this metric with SQL latency and query volume metrics.
`jobs.auto_create_stats.resume_failed`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs.resume{name: auto_create_stats, status: failed}``jobs.auto_create_stats.resume_failed`Number of auto_create_stats jobs which failed with a non-retriable errorThis metric is a high-level indicator that automatically generated table statistics is failing. Failed statistic creation can lead to the query optimizer running with stale statistics. Stale statistics can cause suboptimal query plans to be selected leading to poor query performance.
`jobs.create_stats.currently_running`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{type: create_stats, status: currently_running}``jobs.create_stats.currently_running`Number of create_stats jobs currently running in Resume or OnFailOrCancel stateThis metric tracks the number of active create statistics jobs that could also be consuming resources. Ensure that foreground SQL traffic is not impacted by correlating this metric with SQL latency and query volume metrics.
## Disaster Recovery
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`jobs.backup.currently_paused`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{name: backup, status: currently_paused}``jobs.backup.currently_paused`Number of backup jobs currently considered PausedMonitor and alert on this metric to safeguard against an inadvertent operational error of leaving a backup job in a paused state for an extended period of time. In functional areas, a paused job can hold resources or have concurrency impact or some other negative consequence. Paused backup may break the recovery point objective (RPO).
`jobs.backup.currently_running`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{type: backup, status: currently_running}``jobs.backup.currently_running`Number of backup jobs currently running in Resume or OnFailOrCancel stateSee Description.
`schedules.BACKUP.failed`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `schedules{name: BACKUP, status: failed}``schedules.BACKUP.failed`Number of BACKUP jobs failedMonitor this metric and investigate backup job failures.
`schedules.BACKUP.last-completed-time``schedules.BACKUP.last-completed-time`The unix timestamp of the most recently completed backup by a schedule specified as maintaining this metricMonitor this metric to ensure that backups are meeting the recovery point objective (RPO). Each node exports the time that it last completed a backup on behalf of the schedule. If a node is restarted, it will report 0 until it completes a backup. If all nodes are restarted, max() is 0 until a node completes a backup. To make use of this metric, first, from each node, take the maximum over a rolling window equal to or greater than the backup frequency, and then take the maximum of those values across nodes. For example with a backup frequency of 60 minutes, monitor time() - max_across_nodes(max_over_time(schedules_BACKUP_last_completed_time, 60min)).
## Changefeeds
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`changefeed.commit_latency``changefeed.commit.latency`Event commit latency: a difference between event MVCC timestamp and the time it was acknowledged by the downstream sink. If the sink batches events, then the difference between the oldest event in the batch and acknowledgement is recorded. Excludes latency during backfill.This metric provides a useful context when assessing the state of changefeeds. This metric characterizes the end-to-end lag between a committed change and that change applied at the destination.
`changefeed.emitted_bytes``changefeed.emitted_bytes`Bytes emitted by all feedsThis metric provides a useful context when assessing the state of changefeeds. This metric characterizes the throughput bytes being streamed from the CockroachDB cluster.
`changefeed.emitted_messages``changefeed.emitted_messages`Messages emitted by all feedsThis metric provides a useful context when assessing the state of changefeeds. This metric characterizes the rate of changes being streamed from the CockroachDB cluster.
`changefeed.error_retries``changefeed.error_retries`Total retryable errors encountered by all changefeedsThis metric tracks transient changefeed errors. Alert on "too many" errors, such as 50 retries in 15 minutes. For example, during a rolling upgrade this counter will increase because the changefeed jobs will restart following node restarts. There is an exponential backoff, up to 30 seconds, that resets if the changefeed's resolved timestamp advances between retries. But if there is no rolling upgrade in process or other cluster maintenance, and the error rate is high, investigate the changefeed job.
`changefeed.failures``changefeed.failures`Total number of changefeed jobs which have failedThis metric tracks the permanent changefeed job failures that the jobs system will not try to restart. Any increase in this counter should be investigated. An alert on this metric is recommended.
`changefeed.running``changefeed.running`Number of currently running changefeeds, including sinklessThis metric tracks the total number of all running changefeeds.
`jobs.changefeed.currently_paused`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{name: changefeed, status: currently_paused}``jobs.changefeed.currently_paused`Number of changefeed jobs currently considered PausedMonitor and alert on this metric to safeguard against an inadvertent operational error of leaving a changefeed job in a paused state for an extended period of time. Changefeed jobs should not be paused for a long time because the protected timestamp prevents garbage collection.
`jobs.changefeed.protected_age_sec`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs.protected_age_sec{type: changefeed}``jobs.changefeed.protected_age_sec`The age of the oldest PTS record protected by changefeed jobsChangefeeds use protected timestamps to protect the data from being garbage collected. Ensure the protected timestamp age does not significantly exceed the GC TTL zone configuration. Alert on this metric if the protected timestamp age is greater than 3 times the GC TTL.
## Row-level TTL
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`jobs.row_level_ttl.currently_paused`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{name: row_level_ttl, status: currently_paused}``jobs.row_level_ttl.currently_paused`Number of row_level_ttl jobs currently considered PausedMonitor this metric to ensure the Row Level TTL job does not remain paused inadvertently for an extended period.
`jobs.row_level_ttl.currently_running`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs{type: row_level_ttl, status: currently_running}``jobs.row_level_ttl.currently_running`Number of row_level_ttl jobs currently running in Resume or OnFailOrCancel stateMonitor this metric to ensure there are not too many Row Level TTL jobs running at the same time. Generally, this metric should be in the low single digits.
`jobs.row_level_ttl.delete_duration``jobs.row_level_ttl.delete_duration.count`Duration for delete requests during row level TTL.See Description.
`jobs.row_level_ttl.num_active_spans``jobs.row_level_ttl.num_active_spans`Number of active spans the TTL job is deleting from.See Description.
`jobs.row_level_ttl.resume_completed`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs.resume{name: row_level_ttl, status: completed}``jobs.row_level_ttl.resume_completed.count`Number of row_level_ttl jobs which successfully resumed to completionIf Row Level TTL is enabled, this metric should be nonzero and correspond to the ttl_cron setting that was chosen. If this metric is zero, it means the job is not running
`jobs.row_level_ttl.resume_failed`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `jobs.resume{name: row_level_ttl, status: failed}``jobs.row_level_ttl.resume_failed.count`Number of row_level_ttl jobs which failed with a non-retriable errorThis metric should remain at zero. Repeated errors means the Row Level TTL job is not deleting data.
`jobs.row_level_ttl.rows_deleted``jobs.row_level_ttl.rows_deleted.count`Number of rows deleted by the row level TTL job.Correlate this metric with the metric jobs.row_level_ttl.rows_selected to ensure all the rows that should be deleted are actually getting deleted.
`jobs.row_level_ttl.rows_selected``jobs.row_level_ttl.rows_selected.count`Number of rows selected for deletion by the row level TTL job.Correlate this metric with the metric jobs.row_level_ttl.rows_deleted to ensure all the rows that should be deleted are actually getting deleted.
`jobs.row_level_ttl.select_duration``jobs.row_level_ttl.select_duration.count`Duration for select requests during row level TTL.See Description.
`jobs.row_level_ttl.span_total_duration``jobs.row_level_ttl.span_total_duration.count`Duration for processing a span during row level TTL.See Description.
`jobs.row_level_ttl.total_expired_rows``jobs.row_level_ttl.total_expired_rows`Approximate number of rows that have expired the TTL on the TTL table.See Description.
`jobs.row_level_ttl.total_rows``jobs.row_level_ttl.total_rows`Approximate number of rows on the TTL table.See Description.
`schedules.scheduled-row-level-ttl-executor.failed`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `schedules{name: scheduled-row-level-ttl-executor, status: failed}``schedules.scheduled_row_level_ttl_executor.failed.count`Number of scheduled-row-level-ttl-executor jobs failedMonitor this metric to ensure the Row Level TTL job is running. If it is non-zero, it means the job could not be created.
## Physical Replication
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`physical_replication.cluster.replication_lag`NOT AVAILABLEThe replication lag of the physical replication stream, measured in nanoseconds.Directly reports physical replication lag, without requiring a current time - physical_replication.replicated_time_seconds computation.
`physical_replication.logical_bytes``physical_replication.logical_bytes.count`Logical bytes (sum of keys + values) ingested by all replication jobsTrack PCR throughput
`physical_replication.replicated_time_seconds``physical_replication.replicated_time_seconds`The replicated time of the physical replication stream in seconds since the unix epoch.Track replication lag via current time - physical_replication.replicated_time_seconds
## Logical Replication
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`logical_replication.commit_latency`NOT AVAILABLEEvent commit latency: a difference between event MVCC timestamp and the time it was flushed into disk. If we batch events, then the difference between the oldest event in the batch and flush is recordedtrack the latency of of applying events from source to destination
`logical_replication.events_dlqed`NOT AVAILABLERow update events sent to DLQtrack events sent to the dead letter queue
`logical_replication.events_ingested`NOT AVAILABLEEvents ingested by all replication jobstrack events (e.g. updates, deletes, inserts) ingested
`logical_replication.logical_bytes`NOT AVAILABLELogical bytes (sum of keys + values) received by all replication jobstrack logical data replication throughput
`logical_replication.replicated_time_seconds`NOT AVAILABLEThe replicated time of the logical replication stream in seconds since the unix epoch.Track replication lag via current time - logical_replication.replicated_time_seconds
## Expiration of license and certificates
CockroachDB Metric Name[Datadog Integration Metric Name](https://docs.datadoghq.com/integrations/cockroachdb/?tab=host#metrics)\ (add `cockroachdb.` prefix)DescriptionUsage
`seconds.until.enterprise.license.expiry``seconds.until.enterprise.license.expiry`Seconds until enterprise license expiry (0 if no license present or running without enterprise features)See Description.
`security.certificate.expiration.ca`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=ca}``security.certificate.expiration.ca`Expiration for the CA certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.client-ca`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=client-ca}``security.certificate.expiration.client-ca`Expiration for the client CA certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.client`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=client}``security.certificate.expiration.client`Minimum expiration for client certificates, labeled by SQL user. 0 means no certificate or error.See Description.
`security.certificate.expiration.ui-ca`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=ui-ca}``security.certificate.expiration.ui-ca`Expiration for the UI CA certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.node`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=node}``security.certificate.expiration.node`Expiration for the node certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.node-client`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=node-client}``security.certificate.expiration.node-client`Expiration for the node's client certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.ui`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=ui}``security.certificate.expiration.ui`Expiration for the UI certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.ca-client-tenant`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=ca-client-tenant}``security.certificate.expiration.ca-client-tenant`Expiration for the Tenant Client CA certificate. 0 means no certificate or error.See Description.
`security.certificate.expiration.client-tenant`\ [`metrics` endpoint](prometheus-endpoint#metrics):\ `security.certificate.expiration{certificate_type=client-tenant}``security.certificate.expiration.client-tenant`Expiration for the Tenant Client certificate. 0 means no certificate or error.See Description.
## See also * [Available Metrics](metrics#available-metrics) * [Monitor CockroachDB with Prometheus](monitor-cockroachdb-with-prometheus) * [Visualize metrics in Grafana](monitor-cockroachdb-with-prometheus#step-5-visualize-metrics-in-grafana) * [Custom Chart Debug Page](ui-custom-chart-debug-page) * [Cluster API](cluster-api) * [Essential Alerts](essential-alerts-self-hosted) # Global Tables Source: https://docs.cockroachlabs.com/docs/stable/global-tables In a [multi-region deployment](/docs/v26.4/multiregion-overview#table-locality), [`GLOBAL` table locality](/docs/v26.4/table-localities#global-tables) is a good choice for tables with the following requirements: * Read latency must be low, but write latency can be much higher. * Reads must be up-to-date for business reasons or because the table is referenced by [foreign keys](/docs/v26.4/foreign-key). * Rows in the table, and all latency-sensitive reads, **cannot** be tied to specific regions. In general, this pattern is suited well for reference tables that are rarely updated. Tables with the `GLOBAL` locality can survive zone or region failures, depending on the database-level [survival goal](/docs/v26.4/multiregion-overview#survival-goals) setting. For new clusters using the [multi-region SQL abstractions](/docs/v26.4/multiregion-overview#table-locality), Cockroach Labs recommends lowering the [`--max-offset`](/docs/v26.4/cockroach-start#flags-max-offset) setting to `250ms`. This setting is especially helpful for lowering the write latency of [global tables](/docs/v26.4/table-localities#global-tables). Nodes can run with different values for `--max-offset`, but only for the purpose of updating the setting across the cluster using a rolling upgrade. ## Before you begin ### Fundamentals Multi-region patterns require thinking about the following questions: * What are your [survival goals](/docs/v26.4/multiregion-overview#survival-goals)? Do you need to survive a [zone failure](/docs/v26.4/multiregion-survival-goals#survive-zone-failures)? Do you need to survive a [region failure](/docs/v26.4/multiregion-survival-goals#survive-region-failures)? * What are the [table localities](/docs/v26.4/multiregion-overview#table-locality) that will provide the performance characteristics you need for each table's data? * Do you need low-latency reads and writes from a single region? Do you need that single region to be configurable at the [row level](/docs/v26.4/table-localities#regional-by-row-tables)? Or will [a single optimized region for the entire table](/docs/v26.4/table-localities#regional-tables) suffice? * Do you have a "read-mostly" [table of reference data that is rarely updated](/docs/v26.4/table-localities#global-tables), but that must be read with low latency from all regions? For more information about CockroachDB multi-region capabilities, review the following pages: * [Multi-Region Capabilities Overview](/docs/v26.4/multiregion-overview#table-locality) * [How to Choose a Multi-Region Configuration](/docs/v26.4/choosing-a-multi-region-configuration) * [When to use `ZONE` vs. `REGION` Survival Goals](/docs/v26.4/multiregion-survival-goals#when-to-use-zone-vs-region-survival-goals) * [When to use `REGIONAL` vs. `GLOBAL` Tables](/docs/v26.4/table-localities#when-to-use-regional-vs-global-tables) In addition, reviewing the following information will be helpful: * The concept of [locality](/docs/v26.4/cockroach-start#locality), which CockroachDB uses to place and balance data based on how you define survival goal and table locality settings. * The recommendations in our [Production Checklist](/docs/v26.4/recommended-production-settings), including our [hardware recommendations](/docs/v26.4/recommended-production-settings#hardware). Afterwards, perform a proof of concept to size hardware for your use case. * [SQL Performance Best Practices](/docs/v26.4/performance-best-practices-overview) ### Cluster setup Each [multi-region pattern](/docs/v26.4/topology-patterns#multi-region) assumes the following setup: ![Multi-region hardware setup](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/topology-patterns/topology_multi-region_hardware.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=810cffba5f7294be67bc34e0b3276c28) #### Hardware * 3 regions * Per region, 3+ AZs with 3+ VMs evenly distributed across them * Region-specific app instances and load balancers * Each load balancer redirects to CockroachDB nodes in its region. * When CockroachDB nodes are unavailable in a region, the load balancer redirects to nodes in other regions. #### Cluster startup Start each node with the [`--locality`](/docs/v26.4/cockroach-start#locality) flag specifying its region and AZ combination. For example, the following command starts a node in the `west1` AZ of the `us-west` region: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --locality=region=us-west,zone=west1 \ --certs-dir=certs \ --advertise-addr= [!NOTE] > > Every multi-region database must have a primary region. For more information, see [Database regions](/docs/v26.4/multiregion-overview#database-regions). 1. Issue the following [`ADD REGION`](/docs/v26.4/alter-database#add-region) statements to add the remaining regions to the database: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE test ADD REGION "us-west"; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE test ADD REGION "us-central"; ``` 2. Create a [`GLOBAL` table](/docs/v26.4/table-localities#global-tables) by issuing the following statement: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE TABLE postal_codes ( id INT PRIMARY KEY, code STRING ) LOCALITY GLOBAL; ``` Alternatively, you can set an existing table's locality to `GLOBAL` using [`ALTER TABLE ... SET LOCALITY`](/docs/v26.4/alter-table#set-locality): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > ALTER TABLE postal_codes SET LOCALITY GLOBAL; ``` > [!TIP] > > A good way to check that your [table locality settings](/docs/v26.4/multiregion-overview#table-locality) are having the expected effect is by monitoring how the performance metrics of a workload change as the settings are applied to a running cluster. ## Characteristics ### Latency Global tables support low-latency, global reads of read-mostly data using an extension to CockroachDB's standard transaction protocol called [non-blocking transactions](/docs/v26.4/architecture/transaction-layer#non-blocking-transactions). #### Reads Thanks to the [non-blocking transaction](/docs/v26.4/architecture/transaction-layer#non-blocking-transactions) protocol extension, reads against `GLOBAL` tables access a consistent local replica and therefore never leave the region. This keeps read latency low. #### Writes Writes incur higher latencies than reads, since they require a "commit-wait" step to ensure consistency. For more information about how this works, see [non-blocking transactions](/docs/v26.4/architecture/transaction-layer#non-blocking-transactions). ### Resiliency Because the `test` database does not specify a [survival goal](/docs/v26.4/multiregion-overview#survival-goals), it uses the default [`ZONE` survival goal](/docs/v26.4/multiregion-survival-goals#survive-zone-failures). With the default settings, an entire zone can fail without interrupting access to the database. For more information about how to choose a database survival goal, see [When to Use `ZONE` vs. `REGION` Survival Goals](/docs/v26.4/multiregion-survival-goals#when-to-use-zone-vs-region-survival-goals). ## Troubleshooting ### High follower read latency on global tables Reads on multi-region global tables can experience sporadic high latency on [follower reads](/docs/v26.4/follower-reads) if the round trip time between cluster nodes is higher than 150ms. To work around this issue, consider setting the `kv.closed_timestamp.lead_for_global_reads_override` [cluster setting](/docs/v26.4/cluster-settings) to a value greater than 800ms. The value of `kv.closed_timestamp.lead_for_global_reads_override` will impact write latency to global tables, so you should proceed in 100ms increments until the high read latency no longer occurs. If you've increased the setting to 1500ms and the problem persists, you should [contact support](/docs/v26.4/support-resources). ## Alternatives * If rows in the table, and all latency-sensitive queries, can be tied to specific geographies, consider the [`REGIONAL` Table Locality Pattern](/docs/v26.4/regional-tables) pattern. ## See also * [Multi-Region Capabilities Overview](/docs/v26.4/multiregion-overview#table-locality) * [How to Choose a Multi-Region Configuration](/docs/v26.4/choosing-a-multi-region-configuration) * [When to Use `ZONE` vs. `REGION` Survival Goals](/docs/v26.4/multiregion-survival-goals#when-to-use-zone-vs-region-survival-goals) * [When to Use `REGIONAL` vs. `GLOBAL` Tables](/docs/v26.4/table-localities#when-to-use-regional-vs-global-tables) * [Secondary regions](/docs/v26.4/multiregion-overview#secondary-regions) * [`ALTER DATABASE ... SET SECONDARY REGION`](/docs/v26.4/alter-database#set-secondary-region) * [`ALTER DATABASE ... DROP SECONDARY REGION`](/docs/v26.4/alter-database#drop-secondary-region) * [Topology Patterns Overview](/docs/v26.4/topology-patterns) * Single-region patterns * [Basic Production](/docs/v26.4/topology-basic-production) * Multi-region patterns * [`REGIONAL` Tables](/docs/v26.4/regional-tables) * [`GLOBAL` Tables](/docs/v26.4/global-tables) * [Follower Reads](/docs/v26.4/topology-follower-reads) * [Follow-the-Workload](/docs/v26.4/topology-follow-the-workload) # GSSAPI Authentication (Enterprise) Source: https://docs.cockroachlabs.com/docs/stable/gssapi_authentication CockroachDB supports the Generic Security Services API (GSSAPI) with Kerberos authentication. Although CockroachDB does not support communicating directly with an LDAP service, GSSAPI with Kerberos can be configured to communicate with your LDAP service to authenticate users. ## Requirements * A working Active Directory or Kerberos environment * A Service Principal * A GSSAPI-compatible PostgreSQL Client (psql, etc.) * A client machine with a Kerberos client installed and configured ## Configure KDC for CockroachDB To use Kerberos authentication with CockroachDB, configure a Kerberos service principal name (SPN) for CockroachDB and generate a valid keytab file with the following specifications: * Set the SPN to the name specified by your client driver. For example, if you use the psql client, set SPN to `postgres`. * Create SPNs for all DNS addresses that a user would use to connect to your CockroachDB cluster (including any TCP load balancers between the user and the CockroachDB node) and ensure that the keytab contains the keys for every SPN you create. ### Active Directory For Active Directory, the client syntax for generating a keytab that maps a service principal to the SPN is as follows: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ktpass -out {keytab_filename} \ -princ {Client_SPN}/{NODE/LB_FQDN}@{DOMAIN} \ -mapUser {Service_Principal}@{DOMAIN} \ -mapOp set -pType KRB5_NT_PRINCIPAL +rndPass \ -crypto AES256-SHA1 ``` Example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ktpass -out postgres.keytab \ -princ postgres/loadbalancer1.cockroach.industries@COCKROACH.INDUSTRIES \ -mapUser pguser@COCKROACH.INDUSTRIES \ -mapOp set -pType KRB5_NT_PRINCIPAL +rndPass \ -crypto AES256-SHA1 ``` Copy the resulting keytab to the database nodes. If clients are connecting to multiple addresses (more than one load balancer, or clients connecting directly to nodes), you will need to generate a keytab for each client endpoint. You may want to merge your keytabs together for easier management. You can do this using the `ktpass` command, using the following syntax: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ktpass -out {new_keytab_filename} \ -in {old_keytab_filename} \ -princ {Client_SPN}/{NODE/LB_FQDN}@{DOMAIN} \ -mapUser {Service_Principal}@{DOMAIN} \ -mapOp add \ -pType KRB5_NT_PRINCIPAL +rndPass \ -crypto AES256-SHA1 ``` Example (adds `loadbalancer2` to the above example): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ktpass -out postgres_2lb.keytab \ -in postgres.keytab \ -princ postgres/loadbalancer2.cockroach.industries@COCKROACH.INDUSTRIES \ -mapUser pguser@COCKROACH.INDUSTRIES \ -mapOp add \ -pType KRB5_NT_PRINCIPAL +rndPass \ -crypto AES256-SHA1 ``` ### MIT KDC In MIT KDC, you cannot map a service principal to an SPN with a different username, so you will need to create a service principal that includes the SPN for your client. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} create-user: kadmin.local -q "addprinc {SPN}/{CLIENT_FQDN}@{DOMAIN}" -pw "{initial_password}" ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} create-keytab: kadmin.local -q "ktadd -k keytab {SPN}/{CLIENT_FQDN}@{DOMAIN}" ``` Example: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kadmin.local -q "addprinc postgres/client2.cockroach.industries@COCKROACH.INDUSTRIES" -pw "testing12345!" kadmin.local -q "ktadd -k keytab postgres/client2.cockroach.industries@COCKROACH.INDUSTRIES" ``` Copy the resulting keytab to the database nodes. If clients are connecting to multiple addresses (more than one load balancer, or clients connecting directly to nodes), you will need to generate a keytab for each client endpoint. You may want to merge your keytabs together for easier management. The `ktutil` command can be used to read multiple keytab files and output them into a single output [here](https://web.mit.edu/kerberos/krb5-devel/doc/admin/admin_commands/ktutil.html). ## Configure the CockroachDB node 1. Copy the keytab file to a location accessible by the `cockroach` binary. 2. [Create certificates](/docs/v26.4/cockroach-cert) for inter-node and `root` user authentication: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} mkdir certs my-safe-directory ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach cert create-node \ localhost \ $(hostname) \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach cert create-client root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 3. Provide the path to the keytab in the `KRB5_KTNAME` environment variable. Example: `export KRB5_KTNAME=/home/cockroach/postgres.keytab` 4. Start a CockroachDB node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach start --certs-dir=certs --listen-addr=0.0.0.0 ``` 5. Connect to CockroachDB as `root` using the `root` client certificate generated above: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --certs-dir=certs ``` 6. [Enable an Enterprise license](/docs/v26.4/licensing-faqs#obtain-a-license). > [!NOTE] > > You need the Enterprise license if you want to use the GSSAPI feature. However, if you only want to test that the GSSAPI setup is working, you do not need to enable an Enterprise license. 1. Enable GSSAPI authentication: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET cluster setting server.host_based_authentication.configuration = 'host all all all gss include_realm=0'; ``` Setting the `server.host_based_authentication.configuration` [cluster setting](/docs/v26.4/cluster-settings) to this particular value makes it mandatory for all non-`root` users to authenticate using GSSAPI. The `root` user is always an exception and remains able to authenticate using a valid client cert or a user password. The `include_realm=0` option is required to tell CockroachDB to remove the `@DOMAIN.COM` realm information from the username. We do not support any advanced mapping of GSSAPI usernames to CockroachDB usernames right now. If you want to limit which realms' users can connect, you can also add one or more `krb_realm` parameters to the end of the line as an allowlist, as follows: `host all all all gss include_realm=0 krb_realm=domain.com krb_realm=corp.domain.com` The syntax is based on the `pg_hba.conf` standard for PostgreSQL which is documented [here](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html). It can be used to exclude other users from Kerberos authentication. 2. Create CockroachDB users for every Kerberos user. Ensure the username does not have the `DOMAIN.COM` realm information. For example, if one of your Kerberos users has a username `carl@realm.com`, then you need to create a CockroachDB user with the username `carl`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE USER carl; ``` Grant privileges to the user: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} GRANT ALL ON DATABASE defaultdb TO carl; ``` ## Configure the client 1. Install and configure your Kerberos client: For CentOS/RHEL systems, run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} yum install krb5-user ``` For Ubuntu/Debian systems, run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apt-get install krb5-user ``` Edit the `/etc/krb5.conf` file to include: ``` [libdefaults] default_realm = {REALM} [realms] {REALM} = { kdc = {fqdn-kdc-server or ad-server} admin_server = {fqdn-kdc-server or ad-server} default_domain = {realm-lower-case} } ``` Example: ``` [libdefaults] default_realm = COCKROACH.INDUSTRIES [realms] COCKROACH.INDUSTRIES = { kdc = ad.cockroach.industries admin_server = ad.cockroach.industries default_domain = cockroach.industries } ``` 2. Get a ticket for the db user: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kinit carl ``` 3. Verify if a valid ticket has been generated: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} klist ``` 4. Connect to the cluster using the `cockroach sql` command as the Kerberos user: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --certs-dir=certs -U carl ``` 5. If you specified an Enterprise license earlier, the command succeeds. This indicates that the GSSAPI authentication was successful. Otherwise, the error `ERROR: use of GSS authentication requires an Enterprise license` is shown. ## See also * [Authentication](/docs/v26.4/authentication) * [Create Security Certificates](/docs/v26.4/cockroach-cert) # Install a Driver or ORM Framework Source: https://docs.cockroachlabs.com/docs/stable/install-client-drivers CockroachDB supports both native drivers and the PostgreSQL wire protocol, so most available PostgreSQL client drivers and ORM frameworks should work with CockroachDB. Choose a language for supported clients, and follow the installation steps. After you install a client library, you can [connect to the database](/docs/v26.4/connect-to-the-database). > [!NOTE] > > Applications may encounter incompatibilities when using advanced or obscure features of a driver or ORM framework with **partial** support. If you encounter problems, please [contact Support](/docs/v26.4/support-resources). > [accordion] JavaScript/TypeScript > > View support and resources for pg, Sequelize, Knex.js, TypeORM, or Prisma > > ## JavaScript drivers > > ### pg > > **Support level:** Full > > To install the [Node.js pg driver](https://www.npmjs.com/package/pg): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ npm install pg > ``` > > For a simple but complete example app, see [Build a Node.js App with CockroachDB and the Node.js pg Driver](/docs/v26.4/build-a-nodejs-app-with-cockroachdb). > > ## JavaScript/TypeScript ORM frameworks > > ### Sequelize > > **Support level:** Full > > To install Sequelize and a [CockroachDB Node.js package](https://github.com/cockroachdb/sequelize-cockroachdb) that accounts for some minor differences between CockroachDB and PostgreSQL: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ npm install sequelize sequelize-cockroachdb > ``` > > For a simple but complete example app, see [Build a Node.js App with CockroachDB and Sequelize](/docs/v26.4/build-a-nodejs-app-with-cockroachdb-sequelize). > > ### Knex.js > > **Support level:** Full > > Install Knex.js as described in the [official documentation](https://knexjs.org/#Installation). > > For a simple but complete example app, see [Build a Simple CRUD Node.js App with CockroachDB and Knex.js](/docs/v26.4/build-a-nodejs-app-with-cockroachdb-knexjs). > > ### TypeORM > > **Support level:** Full > > Install TypeORM as described in the [official documentation](https://typeorm.io/#/). > > For a simple but complete example app, see [Build a TypeScript App with CockroachDB and TypeORM](/docs/v26.4/build-a-typescript-app-with-cockroachdb). > > ### Prisma > > **Support level:** Full > > To install the [Prisma ORM](https://prisma.io/): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ npm install prisma > ``` > > For a simple but complete example app, see [Build a Simple CRUD Node.js App with CockroachDB and Prisma](/docs/v26.4/build-a-nodejs-app-with-cockroachdb-prisma). > [accordion] Python > > View support and resources for psycopg3, psycopg2, SQLAlchemy, Django, or peewee > > ## Python drivers > > ### psycopg3 > > **Support level:** Full > > To install the Python psycopg3 driver: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ pip3 install "psycopg[binary]" > ``` > > For other ways to install psycopg3, see the [official documentation](https://www.psycopg.org/psycopg3/docs/basic/install.html). > > For a simple but complete example app, see [Build a Python App with CockroachDB and psycopg3](/docs/v26.4/build-a-python-app-with-cockroachdb-psycopg3). > > ### psycopg2 > > **Support level:** Full > > To install the Python psycopg2 driver: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ pip install psycopg2 > ``` > > For other ways to install psycopg2, see the [official documentation](http://initd.org/psycopg/docs/install.html). > > For a simple but complete example app, see [Build a Python App with CockroachDB and psycopg2](/docs/v26.4/build-a-python-app-with-cockroachdb). > > ## Python ORM frameworks > > ### SQLAlchemy > > **Support level:** Full > > To install SQLAlchemy and a [CockroachDB Python package](https://github.com/cockroachdb/sqlalchemy-cockroachdb) that accounts for some differences between CockroachDB and PostgreSQL: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ pip install sqlalchemy sqlalchemy-cockroachdb psycopg2 > ``` > > > [!TIP] > > > > You can substitute psycopg2 for other alternatives that include the psycopg python package. > > For other ways to install SQLAlchemy, see the [official documentation](http://docs.sqlalchemy.org/intro.html#installation-guide). > > For a simple but complete example app, see [Build a Python App with CockroachDB and SQLAlchemy](/docs/v26.4/build-a-python-app-with-cockroachdb-sqlalchemy). > > ### Django > > **Support level:** Full > > CockroachDB supports Django versions 3.1+. > > To install [Django](https://docs.djangoproject.com/en/4.0/topics/install/): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ pip install django==3.1.* > ``` > > Before installing the [CockroachDB backend for Django](https://github.com/cockroachdb/django-cockroachdb), you must install one of the following psycopg2 prerequisites: > > * [psycopg2](https://pypi.org/project/psycopg2/), which has some > [prerequisites](https://www.psycopg.org/docs/install.html#prerequisites) of > its own. This package is recommended for production environments. > > * [psycopg2-binary](https://pypi.org/project/psycopg2-binary/). This package is recommended for development and testing. > > After you install the psycopg2 prerequisite, you can install the CockroachDB Django backend: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ pip install django-cockroachdb==3.1.* > ``` > > > [!NOTE] > > > > The major version of `django-cockroachdb` must correspond to the major version of `django`. The minor release numbers do not need to match. > > For a simple but complete example app, see [Build a Python App with CockroachDB and Django](/docs/v26.4/build-a-python-app-with-cockroachdb-django). > > ### peewee > > **Support level:** Full > > To install peewee: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ pip install peewee > ``` > > For instructions on using peewee with CockroachDB, see the [CockroachDatabase peewee extension documentation](http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#cockroach-database). > [accordion] Go > > View support and resources for pgx, pq, or GORM > > ## Go drivers > > ### pgx > > **Support level:** Full > > To install the [Go pgx driver](https://pkg.go.dev/github.com/jackc/pgx): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ go get -u github.com/jackc/pgx > ``` > > For a simple but complete example app, see [Build a Go App with CockroachDB and the Go pgx Driver](/docs/v26.4/build-a-go-app-with-cockroachdb). > > ### pq > > **Support level:** Full > > To install the [Go pq driver](https://godoc.org/github.com/lib/pq): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ go get -u github.com/lib/pq > ``` > > For a simple but complete example app, see [Build a Go App with CockroachDB and the Go pq Driver](/docs/v26.4/build-a-go-app-with-cockroachdb). > > ## Go ORM frameworks > > ### GORM > > **Support level:** Full > > To install [GORM](http://gorm.io): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ go get -u github.com/lib/pq # dependency > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ go get -u github.com/jinzhu/gorm > ``` > > For a simple but complete example app, see [Build a Go App with CockroachDB and GORM](/docs/v26.4/build-a-go-app-with-cockroachdb-gorm). > [accordion] Java > > View support and resources for JDBC, Hibernate, or jOOQ > > > [!NOTE] > > > > We recommend using Java versions 8+ with CockroachDB. > > CockroachDB supports TLS 1.2 and 1.3, and uses 1.3 by default. > > CockroachDB supports the [TLS 1.3 and TLS 1.2](https://wikipedia.org/wiki/Transport_Layer_Security) encryption for SQL clients. Starting in CockroachDB v22.2, only cipher suites currently recommended by the IETF ([RFC 8447](https://datatracker.ietf.org/doc/html/rfc8447)) are enabled by default. In v22.2.4 and above, the environment variable `COCKROACH_TLS_ENABLE_OLD_CIPHER_SUITES` can be used to revert to the cipher suite configuration used in version 22.1. This environment variable is not available in v22.2.0-v22.2.3. You should set this environment variable only if you cannot use one of the default cipher suites, but you can use one of the disabled ones. > > CockroachDB supports the [TLS 1.3 and TLS 1.2](https://wikipedia.org/wiki/Transport_Layer_Security) encryption for SQL clients. Only cipher suites currently recommended by the IETF ([RFC 8447](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4)) are enabled by default. The environment variable `COCKROACH_TLS_ENABLE_OLD_CIPHER_SUITES` can be used to revert to the cipher suite configuration used prior to v22.2. You should set this environment variable only if you cannot use one of the default cipher suites, but you can use one of the disabled ones. > > SQL clients, intermediate proxies, or load balancers that do not support any cipher suites that CockroachDB supports will be unable to connect to CockroachDB clusters. For the full list of supported cipher suites, refer to [Supported cipher suites](https://cockroachlabs.com/docs/stable/authentication#supported-cipher-suites). > > [A bug in the TLS 1.3 implementation](https://bugs.openjdk.java.net/browse/JDK-8236039) in Java 11 versions lower than 11.0.7 and Java 13 versions lower than 13.0.3 makes the versions incompatible with CockroachDB. > > If an incompatible version is used, the client may throw the following exception: > > `javax.net.ssl.SSLHandshakeException: extension (5) should not be presented in certificate_request` > > For applications running Java 11 or 13, make sure that you have version 11.0.7 or higher, or 13.0.3 or higher. > > If you cannot upgrade to a version higher than 11.0.7 or 13.0.3, you must configure the application to use TLS 1.2. For example, when starting your app, use: `$ java -Djdk.tls.client.protocols=TLSv1.2 appName` > > ## Java drivers > > ### JDBC > > **Support level:** Full > > Download and set up the latest Java JDBC driver as described in the [official documentation](https://jdbc.postgresql.org/documentation/setup/). > > For a simple but complete example app, see [Build a Java App with CockroachDB and JDBC](/docs/v26.4/build-a-java-app-with-cockroachdb). > > ## Java ORM frameworks > > ### Hibernate > > **Support level:** Full > > You can use [Gradle](https://gradle.org/install) or [Maven](https://maven.apache.org/install.html) to get all dependencies for your application, including Hibernate. Only Hibernate versions 5.4.19 and later support the Hibernate CockroachDB dialect. > > If you are using Gradle, add the following to your `dependencies`: > > ```groovy theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > implementation 'org.hibernate:hibernate-core:{version}.Final' > implementation 'org.postgresql:postgresql:{version}' > ``` > > Where `{version}` is the latest stable version. > > For a simple but complete example app that uses Gradle for dependency management, see [Build a Java App with CockroachDB and Hibernate](/docs/v26.4/build-a-java-app-with-cockroachdb-hibernate). > > If you are using Maven, add the following to your ` > ```xml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > org.hibernate hibernate-core {version}.Final > org.postgresql postgresql ``` > > Where `{version}` is the latest stable version. > > You will also need to specify the CockroachDB dialect in your [Hibernate configuration file](https://www.tutorialspoint.com/hibernate/hibernate_configuration.htm). > > Versions of the Hibernate CockroachDB dialect correspond to the version of CockroachDB installed on your machine. For example, `org.hibernate.dialect.CockroachDB201Dialect` corresponds to CockroachDB v20.1 and later, and `org.hibernate.dialect.CockroachDB192Dialect` corresponds to CockroachDB v19.2 and later. > > All dialect versions are forward-compatible (e.g., CockroachDB v20.1 is compatible with `CockroachDB192Dialect`), as long as your application is not affected by any backward-incompatible changes listed in your CockroachDB version's [release notes](/docs/releases/index). In the event of a CockroachDB version upgrade, using a previous version of the CockroachDB dialect will not break an application, but, to enable all features available in your version of CockroachDB, we recommend keeping the dialect version in sync with the installed version of CockroachDB. > > Not all versions of CockroachDB have a corresponding dialect yet. Use the dialect number that is closest to your installed version of CockroachDB. For example, use `CockroachDB201Dialect` when using CockroachDB v21.1 and later. > > ### jOOQ > > **Support level:** Full > > You can use [Gradle](https://gradle.org/install) or [Maven](https://maven.apache.org/install.html) to get all dependencies for your application, including jOOQ. > > For a simple but complete example app that uses Maven for dependency management, see [Build a Java App with CockroachDB and jOOQ](/docs/v26.4/build-a-java-app-with-cockroachdb-jooq). > [accordion] Ruby > > View support and resources for pg or Active Record > > ## Ruby drivers > > ### pg > > **Support level:** Full > > To install the [Ruby pg driver](https://rubygems.org/gems/pg): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ gem install pg > ``` > > For a simple but complete example app, see [Build a Ruby App with CockroachDB and the Ruby pg Driver](/docs/v26.4/build-a-ruby-app-with-cockroachdb). > > ## Ruby ORM frameworks > > ### Active Record > > **Support level:** Full > > To install Active Record, the [pg driver](https://rubygems.org/gems/pg), and a [CockroachDB Ruby package](https://github.com/cockroachdb/activerecord-cockroachdb-adapter) that accounts for some minor differences between CockroachDB and PostgreSQL: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ gem install activerecord pg activerecord-cockroachdb-adapter > ``` > > > [!NOTE] > > > > The exact command above will vary depending on the desired version of Active Record. Specifically, version 6.0.x of Active Record requires version 6.0.x of the adapter and version 7.0.x of Active Record requires version 7.0.x of the adapter. > > For a simple but complete example app, see [Build a Ruby App with CockroachDB and Active Record](/docs/v26.4/build-a-ruby-app-with-cockroachdb-activerecord). > [accordion] C > > View support and resources for libpq > > ## C drivers > > ### libpq > > **Support level:** Partial > > Install the C libpq driver as described in the [official documentation](https://www.postgresql.org/docs/current/libpq.html). > [accordion] C# (.NET) > > View support and resources for Npgsql > > ## C# drivers > > ### Npgsql > > **Support level:** Full > > 1. Create a .NET project: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ dotnet new console -o cockroachdb-test-app > ``` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cd cockroachdb-test-app > ``` > > The `dotnet` command creates a new app of type `console`. The `-o` parameter creates a directory named `cockroachdb-test-app` where your app will be stored and populates it with the required files. The `cd cockroachdb-test-app` command puts you into the newly created app directory. > > 2. Install the latest version of the [Npgsql driver](https://www.nuget.org/packages/Npgsql/) into the .NET project using the built-in nuget package manager: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ dotnet add package Npgsql > ``` > > For a simple but complete example app, see [Build a C# App with CockroachDB and the .NET Npgsql Driver](/docs/v26.4/build-a-csharp-app-with-cockroachdb). > [accordion] Rust > > View support and resources for rust-postgres > > ## Rust drivers > > ### rust-postgres > > **Support level:** Partial > > Install the Rust-Postgres driver as described in the [official documentation](https://crates.io/crates/postgres). > > For a simple but complete example app, see [Build a Rust App with CockroachDB and the Rust-Postgres Driver](/docs/v26.4/build-a-rust-app-with-cockroachdb). ## What's next? * [Connect to CockroachDB](/docs/v26.4/connect-to-the-database) * [Design a Database Schema](/docs/v26.4/schema-design-overview) You might also be interested in the following pages: * [Third party database tools](/docs/v26.4/third-party-database-tools) * [Connection parameters](/docs/v26.4/connection-parameters) * [Transactions](/docs/v26.4/transactions) * [Performance best practices](/docs/v26.4/performance-best-practices-overview) # Install, Configure, and Connect to the CockroachDB MCP Server Source: https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-mcp-server This page shows how to install the [CockroachDB MCP Server](/docs/stable/cockroachdb-mcp-server), connect it to a cluster, and configure your AI tools to use it. > [!CAUTION] > > AI tools with cluster access can execute operations on your behalf. When first connecting an AI tool to CockroachDB, consider starting with a staging cluster to understand the tool's behavior before granting it access to production data. ## Before you begin * To install with `go install` or build from source, ensure that you have Go 1.26 or later. * Ensure that you have a reachable CockroachDB cluster. For a multi-node cluster, connect through a [load balancer](/docs/stable/recommended-production-settings#load-balancing); for development, you can connect to any node directly. The default port is `26257`. * Create a dedicated [SQL user](/docs/stable/create-user) for the server, and issue [client certificates](/docs/stable/cockroach-cert) for it. * [Grant](/docs/stable/grant) the user only the privileges that the tools you plan to use need. For example, grant `SELECT` on the relevant databases for read-only use. Avoid `admin` and write privileges unless you plan to enable the [write tools](/docs/stable/cockroachdb-mcp-server-reference#write-tools). ## Step 1. Install the server > [tab] Mac > > Pre-built binaries are not available for macOS because a CockroachDB parser dependency requires cgo on macOS. Use one of the following options instead. > > ### Option 1: `go install` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > go install github.com/cockroachdb/cockroachdb-mcp-server@latest > ``` > > The binary lands in `$(go env GOPATH)/bin/cockroachdb-mcp-server`. > > ### Option 2: Build from source > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > git clone https://github.com/cockroachdb/cockroachdb-mcp-server > cd cockroachdb-mcp-server > go build -o bin/cockroachdb-mcp-server . > ./bin/cockroachdb-mcp-server --version > ``` > > ### Option 3: Docker > > Pull the multi-arch image (`linux/amd64`, `linux/arm64`) from Google Artifact Registry: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > docker pull us-docker.pkg.dev/releases-prod/cockroachdb-mcp-server/cockroachdb-mcp-server:{version} > ``` > > The image runs as `nonroot` on a [distroless](https://github.com/GoogleContainerTools/distroless) base image. On Apple Silicon, Docker runs the `linux/arm64` image natively. This is the only install option on macOS that does not require Go. > > To configure an MCP client to run the image, refer to the Docker configuration in [Step 2](#step-2-configure-your-mcp-client). > [tab] Linux > > ### Option 1: Pre-built binaries > > Download a tarball for `linux/amd64` or `linux/arm64` from the [GitHub Releases page](https://github.com/cockroachdb/cockroachdb-mcp-server/releases). > > ### Option 2: `go install` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > go install github.com/cockroachdb/cockroachdb-mcp-server@latest > ``` > > The binary lands in `$(go env GOPATH)/bin/cockroachdb-mcp-server`. > > ### Option 3: Build from source > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > git clone https://github.com/cockroachdb/cockroachdb-mcp-server > cd cockroachdb-mcp-server > go build -o bin/cockroachdb-mcp-server . > ./bin/cockroachdb-mcp-server --version > ``` > > ### Option 4: Docker > > Pull the multi-arch image (`linux/amd64`, `linux/arm64`) from Google Artifact Registry: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > docker pull us-docker.pkg.dev/releases-prod/cockroachdb-mcp-server/cockroachdb-mcp-server:{version} > ``` > > The image runs as `nonroot` on a [distroless](https://github.com/GoogleContainerTools/distroless) base image. > > To configure an MCP client to run the image, refer to the Docker configuration in [Step 2](#step-2-configure-your-mcp-client). > [tab] Windows > > ### Option 1: Pre-built binaries > > Download a `.zip` archive for `windows/amd64` or `windows/arm64` from the [GitHub Releases page](https://github.com/cockroachdb/cockroachdb-mcp-server/releases). > > ### Option 2: `go install` > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > go install github.com/cockroachdb/cockroachdb-mcp-server@latest > ``` > > The binary lands in `%GOPATH%\bin\cockroachdb-mcp-server.exe`. > > ### Option 3: Build from source > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > git clone https://github.com/cockroachdb/cockroachdb-mcp-server > cd cockroachdb-mcp-server > go build -o bin\cockroachdb-mcp-server.exe . > bin\cockroachdb-mcp-server.exe --version > ``` > > ### Option 4: Docker > > Pull the multi-arch image (`linux/amd64`, `linux/arm64`) from Google Artifact Registry: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > docker pull us-docker.pkg.dev/releases-prod/cockroachdb-mcp-server/cockroachdb-mcp-server:{version} > ``` > > The image is built for Linux; on Windows, run it with [Docker Desktop](https://docs.docker.com/desktop/setup/install/windows-install/). The image runs as `nonroot` on a [distroless](https://github.com/GoogleContainerTools/distroless) base image. > > To configure an MCP client to run the image, refer to the Docker configuration in [Step 2](#step-2-configure-your-mcp-client). ## Step 2. Configure your MCP client Each server instance connects to a single cluster. To give your AI tool access to multiple clusters, add one `mcpServers` entry per cluster, each pointing at its own server instance. > [tab] stdio (default) > > In stdio mode, your AI tool launches the server as a subprocess, so all configuration is passed in the `env` block of the tool's MCP configuration. Add one of the following to your MCP client's configuration file, replacing the example values with your own host, user, and certificate paths. Most MCP clients read an `mcpServers` block or an equivalent. Refer to your client's documentation for the file location and format. > > > [!NOTE] > > > > GUI clients such as Claude Desktop often launch with a minimal `PATH` and do not expand `~`, so a bare `command` may not resolve. Use the absolute path to the binary instead, for example `/Users/{username}/go/bin/cockroachdb-mcp-server`. > > ### Specify configuration variables > > #### Certificate authentication (recommended) > > Use [individual variables](/docs/stable/cockroachdb-mcp-server-reference#authentication) to connect with client certificates: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "mcpServers": { > "cockroachdb": { > "command": "cockroachdb-mcp-server", > "env": { > "CRDB_HOST": "my-cluster.crdb.io", > "CRDB_USERNAME": "ai_agent", > "CRDB_SSL_MODE": "verify-full", > "CRDB_SSL_CA_PATH": "/certs/ca.crt", > "CRDB_SSL_CERTFILE": "/certs/client.ai_agent.crt", > "CRDB_SSL_KEYFILE": "/certs/client.ai_agent.key" > } > } > } > } > ``` > > #### Connection string > > Use [`CRDB_DATABASE_URL`](/docs/stable/cockroachdb-mcp-server-reference#crdb-database-url) to pass all connection parameters in a single string: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "mcpServers": { > "cockroachdb": { > "command": "cockroachdb-mcp-server", > "env": { > "CRDB_DATABASE_URL": "postgresql://ai_agent@my-cluster.crdb.io:26257/defaultdb?sslmode=verify-full&sslcert=/certs/client.ai_agent.crt&sslkey=/certs/client.ai_agent.key&sslrootcert=/certs/ca.crt" > } > } > } > } > ``` > > [`CRDB_DATABASE_URL`](/docs/stable/cockroachdb-mcp-server-reference#crdb-database-url) must include an `sslmode` of `require`, `verify-ca`, or `verify-full`. A connection string that omits `sslmode` is rejected at startup. > > #### Local insecure cluster (development only) > > For a local cluster started with `cockroach start-single-node --insecure` or [`cockroach demo --insecure`](/docs/stable/cockroach-demo), opt in to a TLS-free connection. No certificate files are needed: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "mcpServers": { > "cockroachdb": { > "command": "cockroachdb-mcp-server", > "env": { > "CRDB_DATABASE_URL": "postgresql://root@localhost:26257/defaultdb?sslmode=disable", > "CRDB_MCP_ALLOW_INSECURE_DB": "true", > "CRDB_MCP_ENABLE_WRITE_QUERIES": "true" > } > } > } > } > ``` > > For the full list of configuration options, refer to the [CockroachDB MCP Server Reference](/docs/stable/cockroachdb-mcp-server-reference#configuration). > > ### Docker > > To run the Docker image in stdio mode, set `command` to `docker` and move all configuration into `args`: pass `run`, `--rm`, and `-i`, followed by each environment variable with `-e`, and the image reference last. The same `CRDB_*` variables apply unchanged. Because the server runs inside the container, mount the host certificate directory read-only and point the `CRDB_SSL_*` paths at the in-container mount location: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "mcpServers": { > "cockroachdb": { > "command": "docker", > "args": [ > "run", "--rm", "-i", > "-e", "CRDB_HOST=my-cluster.crdb.io", > "-e", "CRDB_USERNAME=ai_agent", > "-e", "CRDB_SSL_MODE=verify-full", > "-e", "CRDB_SSL_CA_PATH=/certs/ca.crt", > "-e", "CRDB_SSL_CERTFILE=/certs/client.ai_agent.crt", > "-e", "CRDB_SSL_KEYFILE=/certs/client.ai_agent.key", > "-v", "/path/to/certs:/certs:ro", > "us-docker.pkg.dev/releases-prod/cockroachdb-mcp-server/cockroachdb-mcp-server:{version}" > ] > } > } > } > ``` > > In this example, `/path/to/certs` is the certificate directory on the host, and `/certs` is where it is mounted inside the container. > > A connection string translates the same way: keep the read-only mount, and use the in-container `/certs` paths in the `sslcert`, `sslkey`, and `sslrootcert` parameters of `CRDB_DATABASE_URL`. > > For a local insecure cluster, `localhost` inside the container refers to the container itself, not the host. On macOS and Windows, use `host.docker.internal` in place of `localhost` in the connection string. On Linux, add `"--network", "host"` to `args` and keep `localhost`. > [tab] HTTP > > For shared or remote deployments, run the server as a long-lived process using the HTTP transport, and point each MCP client at its URL. Replace the example strings with your own. For the full list of [transport variables](/docs/stable/cockroachdb-mcp-server-reference#transport), refer to the reference page. > > In HTTP mode, one server instance binds to exactly one cluster and one SQL user, so every client that connects shares that user's privileges. When multiple projects share a cluster, run a separate instance per project, each with its own least-privilege SQL user and bearer token. > > 1. Export the server configuration and start the server: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > export CRDB_DATABASE_URL="postgresql://..." > export CRDB_MCP_TRANSPORT=http > export CRDB_MCP_HTTP_LISTEN_ADDR=0.0.0.0:8443 > export CRDB_MCP_BEARER_TOKEN="$(openssl rand -hex 32)" > export CRDB_MCP_TLS_CERT=/etc/mcp/tls.crt > export CRDB_MCP_TLS_KEY=/etc/mcp/tls.key > cockroachdb-mcp-server > ``` > > Set [`CRDB_MCP_HTTP_LISTEN_ADDR`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-http-listen-addr) to the `host:port` that fits your deployment: for example, `127.0.0.1:9090` to serve only local traffic behind a TLS-terminating reverse proxy (with [`CRDB_MCP_ALLOW_INSECURE_HTTP`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-allow-insecure-http)`=true`), or `10.0.0.5:8443` to bind a specific interface. > > HTTP mode is TLS-by-default: the server refuses to start without [`CRDB_MCP_TLS_CERT`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-tls-cert) and [`CRDB_MCP_TLS_KEY`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-tls-key) unless [`CRDB_MCP_ALLOW_INSECURE_HTTP`](/docs/stable/cockroachdb-mcp-server-reference#crdb-mcp-allow-insecure-http)`=true` is set (for deployments behind a TLS-terminating reverse proxy). The `/healthz` and `/ready` endpoints are unauthenticated `GET`/`HEAD` probes; all other paths require the bearer token. > > 2. Add the server URL and bearer token to your MCP client's configuration: > > ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > { > "mcpServers": { > "cockroachdb": { > "type": "http", > "url": "https://mcp.example.com:8443", > "headers": { > "Authorization": "Bearer {token}" > } > } > } > } > ``` ## Step 3. Verify the connection Restart your AI tool so that it registers the new MCP configuration, then send a prompt that exercises a read tool. For example: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} List all of the databases in my CockroachDB cluster. ``` ## See also * [CockroachDB MCP Server](/docs/stable/cockroachdb-mcp-server) * [CockroachDB MCP Server Reference](/docs/stable/cockroachdb-mcp-server-reference) * [Connect to the CockroachDB Cloud MCP Server](/docs/cockroachcloud/connect-to-the-cockroachdb-cloud-mcp-server) # Configure JWT Authorization Source: https://docs.cockroachlabs.com/docs/stable/jwt-authorization > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). If you manage users through an identity provider (IdP) that supports JSON Web Tokens (JWT), you can configure CockroachDB to automatically assign [roles](/docs/v26.4/security-reference/authorization) to users based on group claims in their JWT tokens, simplifying access control. If JWT authorization is enabled: 1. When a client connects to the cluster using a JWT token, the cluster extracts the groups claim from the token. 2. If the groups claim is not present in the token, the cluster queries the IdP's userinfo endpoint as a fallback. 3. Each group is mapped to a cluster role by matching the group name to a role name. 4. The user is granted each corresponding role, and roles that the user holds directly but that no longer match the user's groups are revoked. Roles held only indirectly through another role are not revoked individually. Refer to [Role synchronization](#role-synchronization). 5. In conjunction with [automatic user provisioning](/docs/v26.4/sso-sql#configure-user-provisioning) if enabled, users are created automatically during their first authentication and simultaneously receive specified role memberships. ## Prerequisites * Enable [JWT Authentication](/docs/v26.4/sso-sql). * Understand the structure of JWT tokens issued by your identity provider. * Know which claim in your JWT tokens contains group memberships. ## Configuration Before you begin, it may be useful to enable authentication logging, which can help you confirm successful configuration or troubleshoot issues. For details, refer to [Troubleshooting](#troubleshooting). ### Step 1: Enable JWT authorization Enable JWT authorization and configure the groups claim: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Enable JWT authentication (if not already enabled) SET CLUSTER SETTING server.jwt_authentication.enabled = true; -- Enable JWT authorization SET CLUSTER SETTING server.jwt_authentication.authorization.enabled = true; -- Configure the JWT claim containing groups (default: 'groups') SET CLUSTER SETTING server.jwt_authentication.group_claim = 'groups'; -- (Optional) Configure the userinfo endpoint JSON key for groups fallback SET CLUSTER SETTING server.jwt_authentication.userinfo_group_key = 'groups'; ``` > [!NOTE] > > The `userinfo_group_key` setting is only used when the groups claim is missing from the JWT token. CockroachDB will query the IdP's userinfo endpoint using this key to retrieve group memberships. ### Step 2: Configure IdP-specific settings The configuration varies by identity provider: #### Okta Okta typically includes groups in the default `groups` claim: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.jwt_authentication.group_claim = 'groups'; SET CLUSTER SETTING server.jwt_authentication.userinfo_group_key = 'groups'; ``` Example JWT token from Okta: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "iss": "https://your-okta-domain.okta.com", "sub": "00u1abc2def3ghi4jkl", "aud": "your_client_id", "email": "alice@example.com", "groups": ["developers", "team-alpha"] } ``` #### Keycloak For Keycloak Groups (default mapping): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.jwt_authentication.group_claim = 'groups'; ``` Example JWT token: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "iss": "https://keycloak.example.com/realms/myrealm", "sub": "user123", "email": "alice@example.com", "groups": ["developers", "team-alpha"] } ``` > [!NOTE] > > **For Keycloak realm roles**: CockroachDB does not support nested JSON paths like `realm_access.roles`. If you need to use realm roles, create a Keycloak protocol mapper to flatten the roles into a top-level claim: 1. In Keycloak, go to your client settings 2. Navigate to **Mappers** > **Create** 3. Choose **User Realm Role** mapper type 4. Set the **Token Claim Name** to `roles` (or another simple name) 5. Configure CockroachDB to use this claim: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.jwt_authentication.group_claim = 'roles'; ``` #### Azure AD / Microsoft Entra ID Azure AD typically uses the `groups` claim: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.jwt_authentication.group_claim = 'groups'; ``` > [!NOTE] > > In Azure AD, you may need to configure group claims in your app registration. Refer to [Microsoft's documentation](https://learn.microsoft.com/en-us/azure/active-directory/hybrid/connect/how-to-connect-fed-group-claims) for details. ### Step 3: Create matching roles Create CockroachDB roles that match your IdP group names and grant appropriate privileges to each role. Remember that role names must comply with CockroachDB's [identifier requirements](/docs/v26.4/create-user#user-names). > [!NOTE] > > Group names from the IdP are normalized using case folding and Unicode normalization (NFC) before matching to role names. This means that group names are typically converted to lowercase for matching purposes. For example, if your JWT tokens contain groups named `developers` and `analysts`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Create role for developers CREATE ROLE developers; GRANT ALL ON DATABASE app TO developers; -- Create role for analysts CREATE ROLE analysts; GRANT SELECT ON DATABASE analytics TO analysts; ``` > [!NOTE] > > If you are going to use [automatic user provisioning](/docs/v26.4/sso-sql#configure-user-provisioning) in conjunction with JWT authorization, be sure to complete the creation of group roles before enabling automatic user provisioning. Auto-provisioned users will only receive roles for groups that already exist as CockroachDB roles. ### Step 4: Confirm configuration 1. On your identity provider, set up test users with memberships in groups that should be synced to CockroachDB roles. 2. If [automatic user provisioning](/docs/v26.4/sso-sql#configure-user-provisioning) is not enabled, create the matching test users when logged in as an admin to CockroachDB: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE username1 LOGIN; CREATE ROLE username2 LOGIN; CREATE ROLE username3 LOGIN; ``` If automatic user provisioning is enabled, users will be created automatically during their first login. 3. Obtain a JWT token from your identity provider and connect to CockroachDB using the token. Refer to [Authenticate to your cluster](/docs/v26.4/sso-sql#authenticate-to-your-cluster). 4. Using your `admin` credentials, log in to the CockroachDB SQL shell and verify the user's role assignments: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- View roles granted to a specific user SHOW GRANTS FOR username1; -- Check if user has a specific role SELECT pg_has_role('username1', 'developers', 'member'); ``` For auto-provisioned users, you can identify them by their `PROVISIONSRC` role option: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- View all users and their provisioning source SELECT rolname, rolprovisionsrc FROM pg_roles WHERE rolprovisionsrc LIKE 'jwt_token:%'; ``` ## How it works ### Group extraction process When a user authenticates with a JWT token and JWT authorization is enabled: 1. **Token validation**: CockroachDB first validates the JWT token signature, issuer, and claims. 2. **Group extraction**: * CockroachDB looks for the configured `group_claim` (default: `groups`) in the JWT token. * If the claim is missing or cannot be parsed, CockroachDB queries the IdP's userinfo endpoint and looks for the `userinfo_group_key` (default: `groups`). > [!NOTE] > > **Groups claim format**: The groups claim is expected to be a JSON array of strings, for example `["developers", "analysts"]`. If the claim is a single string instead, CockroachDB splits it on commas only, so `"developers,analysts"` yields two groups, while a group name that contains spaces, such as `"data platform"`, is treated as one group. Each name is trimmed of surrounding whitespace and lowercased, empty entries are dropped, and duplicates are removed. The same parsing applies to the value of `userinfo_group_key` in the userinfo response. Identity providers that convey multiple groups should return a JSON array. 3. **Normalization**: Group names are normalized using `MakeSQLUsernameFromUserInput`, which performs case folding and Unicode normalization (NFC). 4. **Role matching**: Each normalized group name is compared against existing CockroachDB roles. ### Role synchronization On each login, CockroachDB synchronizes the user's role memberships: 1. **Grant new roles**: If a group matches an existing role name and the user doesn't already have that role, it is granted. 2. **Revoke stale roles**: If the user [directly](/docs/v26.4/security-reference/authorization#direct-member) holds roles that don't match any current groups, those roles are revoked. Only the user's direct role memberships are reconciled; roles the user holds [indirectly](/docs/v26.4/security-reference/authorization#indirect-member) through a directly granted role are not revoked individually. For example, if the user was directly granted `developers`, and `developers` is itself a member of `app_readers`, the user holds `app_readers` indirectly. If the IdP then lists only `app_readers`, CockroachDB revokes `developers` and grants `app_readers` directly. 3. **Skip non-existent roles**: If a group doesn't match any existing role, it is silently skipped (no error is raised). > [!NOTE] > > IdP groups that don't correspond to CockroachDB roles are silently ignored. You must pre-create roles in CockroachDB for them to be granted. ### Empty groups behavior If the groups claim exists but contains an empty array (`[]`): 1. All role memberships that the user holds directly are revoked. 2. Login is **rejected** with error: `JWT authorization: empty group list` This behavior ensures that users without group memberships cannot access the cluster, which is a security feature to prevent unauthorized access. ### Userinfo endpoint fallback If the JWT token does not contain the configured groups claim, CockroachDB will attempt to query the IdP's userinfo endpoint: 1. CockroachDB makes an HTTP GET request to the userinfo endpoint using the access token. 2. The response is parsed as JSON, and CockroachDB looks for the `userinfo_group_key`. 3. If the userinfo lookup fails, login is rejected with error: `JWT authorization: userinfo lookup failed`. The user's role memberships are not modified. ## Troubleshooting Enable [`SESSION` logging](/docs/v26.4/logging#sessions) to preserve data that will help troubleshoot JWT authorization issues: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.auth_log.sql_sessions.enabled = true; ``` > [!NOTE] > > Once all functionality is configured and tested successfully, we recommend disabling session logging to conserve system resources. To view the logs, open `cockroach-session.log` from your [logging directory](/docs/v26.4/configure-logs#logging-directory). Potential issues to investigate may pertain to: * **JWT token validation**: Ensure the token is properly signed and issued by a trusted issuer. * **Missing groups claim**: Check if the token contains the configured claim name. Use a JWT decoder tool to inspect the token. * **Claim name mismatch**: Verify that `server.jwt_authentication.group_claim` matches the actual claim name in your tokens. * **Userinfo endpoint**: If relying on userinfo fallback, ensure the endpoint is accessible and returns the expected JSON structure. * **Role name mismatches**: Remember that group names are normalized (typically lowercased). Check that your role names match the normalized group names. * **Empty groups**: Verify that users have group memberships in the IdP. ### Common errors **Error**: `JWT authorization: empty group list` * **Cause**: The groups claim exists but contains an empty array. * **Solution**: Ensure users have appropriate group memberships in your identity provider. **Error**: `JWT authorization: userinfo lookup failed` * **Cause**: The token doesn't contain the groups claim, and the userinfo endpoint query failed. * **Solution**: Either include groups in the JWT token or ensure the userinfo endpoint is accessible and configured correctly. **Error**: User can log in but has no privileges * **Cause**: Groups from the IdP don't match any existing CockroachDB roles. * **Solution**: Create roles with names matching the normalized group names from your IdP. ## Security considerations 1. **Maintain backup authentication**: Always keep a backup authentication method (like password or client certificate) for administrative users in case of IdP outages. 2. **Validate token issuers**: Ensure `server.jwt_authentication.issuers` is properly configured to accept only trusted issuers. 3. **Pre-create roles with minimal privileges**: Create roles before enabling authorization and grant only the necessary privileges following the principle of least privilege. 4. **Monitor role synchronization**: Regularly audit role assignments and changes. Enable audit logging if available to track when roles are granted or revoked. 5. **Secure the userinfo endpoint**: If using userinfo fallback, ensure the endpoint requires proper authentication and is only accessible over HTTPS. 6. **Review empty groups policy**: Understand that empty groups will block login. Ensure this aligns with your security requirements. 7. **Regularly audit IdP groups**: Review and clean up group memberships in your identity provider to ensure they reflect current access requirements. ## See also * [Cluster Single Sign-on (SSO) using JWTs](/docs/v26.4/sso-sql) * [SASL OAUTHBEARER (OAuth 2.0) Authentication for SQL Clients](/docs/v26.4/oauth-authentication) * [LDAP Authorization](/docs/v26.4/ldap-authorization) * [OIDC Authorization](/docs/v26.4/oidc-authorization) * [Authorization](/docs/v26.4/security-reference/authorization) * [Security Reference: Authorization](/docs/v26.4/security-reference/authorization) # Legacy Kubernetes Deployment Deprecation Notice Source: https://docs.cockroachlabs.com/docs/stable/kubernetes-deprecation-notice The following two deployment options are now considered "legacy" and will be deprecated in a future release, with a support timeline for existing and upcoming CockroachDB versions. ## Public Kubernetes operator support The [Public operator](https://github.com/cockroachdb/cockroach-operator) for CockroachDB is now considered "legacy" and will be deprecated in 2027, in favor of the fully-supported [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview). The legacy public operator will continue to be available and supported until the end of maintenance support for all current and future [supported major versions of CockroachDB](/docs/releases/release-support-policy#support-types) through v27.2. CockroachDB v27.3, expected to release in July 2027, will no longer support the legacy public operator. Existing deployments will need to [migrate to the CockroachDB operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) before upgrading to v27.3 or later. ## Helm StatefulSet support The CockroachDB deployment option of using Helm to deploy CockroachDB nodes as a StatefulSet is now considered a legacy deployment method that will remain fully supported through CockroachDB v27.2, and no longer supported in version v27.3 or later. All new Kubernetes deployments are strongly recommended to use the [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) and existing Helm StatefulSet deployments will need to [migrate to the CockroachDB operator](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) before upgrading to v27.3 or later. # Kubernetes Overview Source: https://docs.cockroachlabs.com/docs/stable/kubernetes-overview Kubernetes is a portable, extensible platform for managing containerized workloads and services. For a given workload, you provide Kubernetes with a configuration, and Kubernetes applies that configuration to all Kubernetes nodes that are running the application. > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). You can also deploy CockroachDB on Kubernetes using the following methods: * [Public operator](https://github.com/cockroachdb/cockroach-operator) The Public operator is also available on platforms such as [Red Hat OpenShift](/docs/v26.4/deploy-cockroachdb-with-kubernetes-openshift) and [IBM Cloud Pak for Data](https://www.ibm.com/products/cloud-pak-for-data). * Manual [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) configuration * [Helm](https://helm.sh/) package manager for Kubernetes ## CockroachDB on Kubernetes This section describes how to: * [Deploy CockroachDB on a single Kubernetes cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes) * [Deploy CockroachDB on Red Hat OpenShift](/docs/v26.4/deploy-cockroachdb-with-kubernetes-openshift) * [Orchestrate CockroachDB across multiple Kubernetes clusters](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster) ## Kubernetes terminology Before starting, review some basic Kubernetes terminology. Note that CockroachDB [nodes](/docs/v26.4/architecture/glossary#cockroachdb-architecture-terms) are distinct from Kubernetes "nodes" or "worker nodes". | Feature | Description | | - | - | | [node](https://kubernetes.io/docs/concepts/architecture/nodes/) | A physical or virtual machine. In the [deployment tutorial](/docs/v26.4/deploy-cockroachdb-with-kubernetes), you'll create GCE or AWS instances and join them as worker nodes into a single Kubernetes cluster from your local workstation. | | [pod](http://kubernetes.io/docs/user-guide/pods/) | A pod is a group of one of more Docker containers. In the [deployment tutorial](/docs/v26.4/deploy-cockroachdb-with-kubernetes), each pod will run on a separate Kubernetes worker node and include one Docker container running a single CockroachDB node, reflecting our [topology recommendations](/docs/v26.4/recommended-production-settings#topology). | | [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) | A StatefulSet is a group of pods treated as stateful units, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart. StatefulSets are considered stable as of Kubernetes version 1.9 after reaching beta in version 1.5. | | [persistent volume](http://kubernetes.io/docs/user-guide/persistent-volumes/) | A persistent volume is a piece of networked storage (Persistent Disk on GCE, Elastic Block Store on AWS) mounted into a pod. The lifetime of a persistent volume is decoupled from the lifetime of the pod that's using it, ensuring that each CockroachDB node binds back to the same storage on restart. The [deployment tutorial](/docs/v26.4/deploy-cockroachdb-with-kubernetes) assumes that dynamic volume provisioning is available. When that is not the case, [persistent volume claims](http://kubernetes.io/docs/user-guide/persistent-volumes/#persistentvolumeclaims) need to be created manually. | | [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) | RBAC, or Role-Based Access Control, is the system Kubernetes uses to manage permissions within the cluster. In order to take an action (e.g., `get` or `create`) on an API resource (e.g., a `pod`), the client must have a `Role` that allows it to do so. The [deployment tutorial](/docs/v26.4/deploy-cockroachdb-with-kubernetes) creates the RBAC resources necessary for CockroachDB to create and access certificates. | # CockroachDB Performance on Kubernetes Source: https://docs.cockroachlabs.com/docs/stable/kubernetes-performance Kubernetes provides many useful abstractions for deploying and operating distributed systems, but some of the abstractions come with a performance overhead and an increase in underlying system complexity. This page explains potential bottlenecks to be aware of when [running CockroachDB in Kubernetes](/docs/v26.4/kubernetes-overview) and shows you how to optimize your deployment for better performance. This page is for Kubernetes deployments that are not using the CockroachDB operator. For guidance specific to the CockroachDB operator, read [CockroachDB Performance on Kubernetes with the CockroachDB operator](/docs/v26.4/cockroachdb-operator-performance). > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). ## Before you begin Before you focus on optimizing a Kubernetes-orchestrated CockroachDB cluster: 1. Before deploying on Kubernetes, ensure that performance is optimized for your workload on identical hardware. You may find that you first need to [modify your workload](/docs/v26.4/performance-best-practices-overview) or use [different machine specs](/docs/v26.4/recommended-production-settings#hardware) to achieve the performance you need. 2. Go through the documentation for [deploying CockroachDB in a single Kubernetes cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes) to familiarize yourself with the necessary Kubernetes terminology and deployment abstractions. ## Performance factors A number of independent factors affect performance when running CockroachDB on Kubernetes. Most are easiest to change before you create your CockroachDB cluster. If you need to modify a CockroachDB cluster that is already running on Kubernetes, extra care and testing is strongly recommended. The following sections show how to modify excerpts from our provided Kubernetes configuration YAML files. You can find the most up-to-date versions of these files on GitHub: [one for running CockroachDB in secure mode](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cockroachdb-statefulset-secure.yaml) and one for [running CockroachDB in insecure mode](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/cockroachdb-statefulset.yaml). You can also use a [performance-optimized configuration file for secure mode](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/performance/cockroachdb-statefulset-secure.yaml) or [insecure mode](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/performance/cockroachdb-statefulset-insecure.yaml). Be sure to modify the file wherever there is a `TODO` comment. ### Version of CockroachDB Because CockroachDB is under very active development, there are typically substantial performance gains in each release. If you aren't running the latest release and aren't getting the performance you desire, you should try the latest and see how much it helps. ### Client workload Your workload is the single most important factor in database performance. Read through our [SQL performance best practices](/docs/v26.4/performance-best-practices-overview) to determine whether there are any easy changes that you can make to speed up your application. ### Machine size The size of the machines you're using isn't a Kubernetes-specific concern, but it's always a good place to start if you want more performance. See our [hardware recommendations](/docs/v26.4/recommended-production-settings#hardware) for specific suggestions, but using machines with more CPU will almost always allow for greater throughput. Be aware that because Kubernetes runs a set of processes on every machine in a cluster, you typically will get more bang for your buck by using fewer large machines than more small machines. ### Disk type CockroachDB makes heavy use of the disks you provide it, so using faster disks is an easy way to improve your cluster's performance. Our provided configuration does not specify what type of disks it wants, so in most environments Kubernetes will auto-provision disks of the default type. In the common cloud environments (AWS, GCP, Azure) this means you'll get slow disks that aren't optimized for database workloads (e.g.,HDDs on GCE, SSDs without provisioned IOPS on AWS). However, we [strongly recommend using SSDs](/docs/v26.4/recommended-production-settings#hardware) for the best performance, and Kubernetes makes it relatively easy to use them. #### Creating a different disk type Kubernetes exposes the disk types used by its volume provisioner via its [`StorageClass` API object](https://kubernetes.io/docs/concepts/storage/storage-classes/). Each cloud environment has its own default `StorageClass`, but you can easily change the default or create a new named class which you can then ask for when asking for volumes. To do this, pick the type of volume provisioner you want to use from the list in the [Kubernetes documentation](https://kubernetes.io/docs/concepts/storage/storage-classes/), take the example YAML file they provide, modify it to have the disk type you want, then run `kubectl create -f `. For example, in order to use the `pd-ssd` disk type on Google Compute Engine or Google Kubernetes Engine, you can use a `StorageClass` file like this: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: provisioner: kubernetes.io/gce-pd parameters: type: pd-ssd ``` You can then use this new disk type either by configuring the CockroachDB YAML file to request it or by making it the default. You may also want to set additional parameters as documented in the list of Kubernetes storage classes, such as configuring the `iopsPerGB` if you're creating a `StorageClass` for AWS's `io1` Provisioned IOPS volume type. #### Configuring the disk type used by CockroachDB To use a new `StorageClass` without making it the default in your cluster, you have to modify your application's YAML file to ask for it. In the CockroachDB StatefulSet configuration, that means adding a line to its `VolumeClaimTemplates` section. For example, that would mean taking these lines of the CockroachDB config file: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} volumeClaimTemplates: - metadata: name: datadir spec: accessModes: - "ReadWriteOnce" resources: requests: storage: 1Gi ``` And adding a `storageClassName` field to the `spec`, changing them to: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} volumeClaimTemplates: - metadata: name: datadir spec: accessModes: - "ReadWriteOnce" storageClassName: resources: requests: storage: 1Gi ``` If you make this change then run `kubectl create -f` on your YAML file, Kubernetes should create volumes for you using your new `StorageClass`. #### Changing the default disk type If you want your new `StorageClass` to be the default for all volumes in your cluster, you have to run a couple of commands to inform Kubernetes of what you want. First, get the names of your `StorageClass`es. Then remove the current default and add yours as the new default. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get storageclasses ``` ``` NAME PROVISIONER ssd kubernetes.io/gce-pd standard (default) kubernetes.io/gce-pd ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch storageclass standard -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' ``` ``` storageclass "standard" patched ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch storageclass ssd -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' ``` ``` storageclass "ssd" patched ``` Note that if you are running an older version of Kubernetes, you may need to use a beta version of the annotation instead of the form used above. In particular, on v1.8 of Kubernetes you need to use `storageclass.beta.kubernetes.io/is-default-class`. To determine for sure which to use, run `kubectl describe storageclass` and copy the annotation used by the current default. ### Disk size On some cloud providers (notably including all GCP disks and the AWS io1 disk type), the number of IOPS available to a disk is directly correlated to the size of the disk. In such cases, increasing the size of your disks can make for significantly better CockroachDB performance, as well as less risk of filling them up. Doing so is easy -- before you create your CockroachDB cluster, modify the `VolumeClaimTemplate` in the CockroachDB YAML file to ask for more space. For example, to give each CockroachDB instance 1TB of disk space, you'd change: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} volumeClaimTemplates: - metadata: name: datadir spec: accessModes: - "ReadWriteOnce" resources: requests: storage: 1Gi ``` To instead be: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} volumeClaimTemplates: - metadata: name: datadir spec: accessModes: - "ReadWriteOnce" resources: requests: storage: 1024Gi ``` Since [GCE disk IOPS scale linearly with disk size](https://cloud.google.com/compute/docs/disks/performance#type_comparison), a 1TiB disk gives 1024 times as many IOPS as a 1GiB disk, which can make a very large difference for write-heavy workloads. ### Local disks Up to this point, we have assumed the use of auto-provisioned, remotely attached disks. However, local disks typically provide better performance than remotely attached disks. For example, SSD Instance Store Volumes outperform EBS Volumes on AWS, and Local SSDs outperform Persistent Disks on GCE. As of v1.14, Kubernetes supports [`local` volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local). Note that when running with local disks, there is a greater chance of experiencing a disk failure than when using the cloud providers' network-attached disks that are often replicated underneath the covers. Consequently, you may want to [Replication Controls](/docs/v26.4/configure-replication-zones) to increase the replication factor of your data to 5 from its default of 3 when using local disks. ### Resource requests and limits When you ask Kubernetes to run a pod, either directly or indirectly through another resource type such as a StatefulSet, you can tell it to reserve certain amounts of CPU and/or memory for each container in the pod or to limit the CPU and/or memory of each container. Doing one or both of these can have different implications depending on how utilized your Kubernetes cluster is. For the authoritative information on this topic, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/). #### Resource requests Resource requests allow you to reserve a certain amount of CPU or memory for your container. If you add resource requests to your CockroachDB YAML file, Kubernetes will schedule each CockroachDB pod onto a node with sufficient unreserved resources and will ensure the pods are guaranteed the reserved resources using the applicable Linux container primitives. If you are running other workloads in your Kubernetes cluster, setting resource requests is very strongly recommended to ensure good performance, because if you do not set them then CockroachDB could be starved of CPU cycles or [OOM stopped](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash) before less important processes. To determine how many resources are usable on your Kubernetes nodes, you can run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl describe nodes ``` ``` Name: gke-perf-default-pool-aafee20c-k4t8 [...] Capacity: cpu: 4 memory: 15393536Ki pods: 110 Allocatable: cpu: 3920m memory: 12694272Ki pods: 110 [...] Non-terminated Pods: (2 in total) Namespace Name CPU Requests CPU Limits Memory Requests Memory Limits --------- ---- ------------ ---------- --------------- ------------- kube-system kube-dns-778977457c-kqtlr 260m (6%) 0 (0%) 110Mi (0%) 170Mi (1%) kube-system kube-proxy-gke-perf-default-pool-aafee20c-k4t8 100m (2%) 0 (0%) 0 (0%) 0 (0%) Allocated resources: (Total limits may be over 100 percent, i.e., overcommitted.) CPU Requests CPU Limits Memory Requests Memory Limits ------------ ---------- --------------- ------------- 360m (9%) 0 (0%) 110Mi (0%) 170Mi (1%) ``` This will output a lot of information for each of the nodes in your cluster, but if you focus in on the right parts you'll see how many "allocatable" resources are available on each node and how many resources are already being used by other pods. The "allocatable" resources are how much CPU and memory Kubernetes is willing to provide to pods running on the machine. The difference between the node's "capacity" and its "allocatable" resources is taken up by the operating system and Kubernetes's management processes. The "m" in "3920m" stands for "milli-CPUs", meaning "thousandths of a CPU". You'll also see a number of pods running here that you may not have realized were in your cluster. Kubernetes runs a handful of pods in the `kube-system` namespace that are part of the cluster infrastructure. These may make it tough to attempt to reserve all the allocatable space on your nodes for CockroachDB, since some of them are essential for the Kubernetes cluster's health. If you want to run CockroachDB on every node in your cluster, you'll have to leave room for these processes. If you are only running CockroachDB on a subset of the nodes in your cluster, you can choose to take up all the "allocatable" space other than what is being used by the `kube-system` pods that are on all the nodes in the cluster, such as `kube-proxy` or the `fluentd` logging agent. Note that it will be difficult to truly use up all of the allocatable space in the current versions of Kubernetes (v1.10 or older) because you'd have to manually preempt the `kube-system` pods that are already on the nodes you want CockroachDB to run on (by deleting them). This should become easier in future versions of Kubernetes when its [Pod Priority](https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/) feature gets promoted from alpha to beta. Once that feature is more widely available, you could set the CockroachDB pods to a higher priority, causing the Kubernetes scheduler to preempt and reschedule the `kube-system` pods onto other machines. Once you've picked out an amount of CPU and memory to reserve for Cockroach, you'll have to configure the resource request in your CockroachDB YAML file. They should go underneath the `containers` heading. For example, to use most of the available resources on the machines described above, you'd change these lines of your YAML config file: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} containers: - name: cockroachdb image: : imagePullPolicy: IfNotPresent ports: - containerPort: 26257 name: grpc - containerPort: 8080 name: http ``` To be: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} containers: - name: cockroachdb image: : imagePullPolicy: IfNotPresent resources: requests: cpu: "3500m" memory: "12300Mi" ports: - containerPort: 26257 name: grpc - containerPort: 8080 name: http ``` When you create the StatefulSet, you'll want to check to make sure that all the CockroachDB pods are scheduled successfully. If you see any get stuck in the pending state, run `kubectl describe pod ` and check the `Events` for information about why they're still pending. You may need to manually preempt pods on one or more nodes by running `kubectl delete pod` on them to make room for the CockroachDB pods. As long as the pods you delete were created by a higher-level Kubernetes object such as a `Deployment` or a StatefulSet, they'll be safely recreated on another node. #### Resource limits Resource limits are conceptually similar to resource requests, but serve a different purpose. They let you cap the resources used by a pod to no more than the provided limit, which can have a couple of different uses. For one, it makes for more predictable performance because your pods will not be allowed to use any excess capacity on their machines, meaning that they will not have more resources available to them at some times (during lulls in traffic) than others (busy periods where the other pods on a machine are also fully utilizing their reserved resources). Secondly, it also increases the ["Quality of Service" guaranteed by the Kubernetes runtime](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/resource-qos.md) on Kubernetes versions 1.8 and below, making the pods less likely to be preempted when a machine is oversubscribed. Finally, memory limits in particular limit the amount of memory that the container knows is available to it, which help when you specify percentages for the CockroachDB `--cache` and `--max-sql-memory` flags, as our default configuration file does. Setting resource limits works about the same as setting resource requests. If you wanted to set resource limits in addition to requests on the config from the [Resource Requests](#resource-requests) section above, you'd change the config to: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} containers: - name: cockroachdb image: : imagePullPolicy: IfNotPresent resources: requests: cpu: "3500m" memory: "12300Mi" limits: cpu: "3500m" memory: "12300Mi" ports: - containerPort: 26257 name: grpc - containerPort: 8080 name: http ``` The pods would then be restricted to only use the resource they have reserved and guaranteed to not be preempted except in very exceptional circumstances. This typically will not give you better performance on an under-utilized Kubernetes cluster, but will give you more predictable performance as other workloads are run. #### Default resource requests and limits Note that even if you do not manually set resource requests yourself, you're likely unknowingly using them anyways. In many installations of Kubernetes, a [`LimitRange`](https://kubernetes.io/docs/tasks/administer-cluster/cpu-default-namespace/) is preconfigured for the `default` namespace that applies a default CPU request of `100m`, or one-tenth of a CPU. You can see this configuration by running ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl describe limitranges ``` ``` Name: limits Namespace: default Type Resource Min Max Default Request Default Limit Max Limit/Request Ratio ---- -------- --- --- --------------- ------------- ----------------------- Container cpu - - 100m - - ``` Experimentally, this does not appear to have a noticeable effect on CockroachDB's performance when a Kubernetes cluster isn't heavily utilized, but do not be surprised if you see CPU requests on your pods that you didn't set. ### Other pods on the same machines as CockroachDB As discovered in the above section on [Resource Requests and Limits](#resource-requests-and-limits), there will always be pods other than just CockroachDB running in your Kubernetes cluster, even if you do not create any other pods of your own. You can see them at any time by running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --all-namespaces ``` ``` NAMESPACE NAME READY STATUS RESTARTS AGE kube-system event-exporter-v0.1.7-5c4d9556cf-6v7lf 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-6rvmk 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-m2xgp 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-sfgps 2/2 Running 0 2m kube-system fluentd-gcp-v2.0.9-szwwn 2/2 Running 0 2m kube-system heapster-v1.4.3-968544ffd-5tsb8 3/3 Running 0 1m kube-system kube-dns-778977457c-4s7vv 3/3 Running 0 1m kube-system kube-dns-778977457c-ls6fq 3/3 Running 0 2m kube-system kube-dns-autoscaler-7db47cb9b7-x2cc4 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-dbn0 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-nr06 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-rc4m 1/1 Running 0 2m kube-system kube-proxy-gke-test-default-pool-828d39a7-trd1 1/1 Running 0 2m kube-system kubernetes-dashboard-768854d6dc-v7ng8 1/1 Running 0 2m kube-system l7-default-backend-6497bcdb4d-2kbh4 1/1 Running 0 2m ``` These ["cluster add-ons"](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons) provide a variety of basic services like managing DNS entries for services within the cluster, powering the Kubernetes dashboard UI, or collecting logs or metrics from all the pods running in the cluster. If you do not like having them take up space in your cluster, you can prevent some of them from running by configuring your Kubernetes cluster appropriately. For example, on GKE, you can create a cluster with the minimal set of addons by running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters create --no-enable-cloud-logging --no-enable-cloud-monitoring --addons="" ``` However, essentials like `kube-proxy` and `kube-dns` are effectively required to have a compliant Kubernetes cluster. This means that you'll always have some pods that aren't yours running in your cluster, so it's important to understand and account for the possible effects of CockroachDB having to share a machine with other processes. The more processes there are on the same machine as a CockroachDB pod, the worse and less predictable its performance will likely be. To protect against this, it's strongly recommended to run with [Resource Requests](#resource-requests) on your CockroachDB pods to provide some level of CPU and memory isolation. Setting resource requests isn't a panacea, though. There can still be contention for shared resources like network I/O or, in [exceptional](https://sysdig.com/blog/container-isolation-gone-wrong/) cases, internal kernel data structures. For these reasons and because of the Kubernetes infrastructure processes running on each machine, CockroachDB running on Kubernetes simply cannot reach quite the same levels of performance as running directly on dedicated machines. Thankfully, it can at least get quite close if you use Kubernetes wisely. If for some reason setting appropriate resource requests still isn't getting you the performance you expect, you might want to consider going all the way to [dedicated nodes](#dedicated-nodes). #### Client applications on the same machines as CockroachDB Running client applications such as benchmarking applications on the same machines as CockroachDB can be even worse than just having Kubernetes system pods on the same machines. They are very likely to end up competing for resources, because when the applications get more loaded than usual, so will the CockroachDB processes. The best way to avoid this is to [set resource requests and limits](#resource-requests-and-limits), but if you are unwilling or unable to do that for some reason, you can also set [anti-affinity scheduling policies](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity) on your client applications. Anti-affinity policies are placed in the pod spec, so if you wanted to change our provided example load generator app, you'd change [these lines](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/example-app.yaml): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: containers: ``` To be: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - loadgen topologyKey: kubernetes.io/hostname - weight: 99 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - cockroachdb topologyKey: kubernetes.io/hostname containers: ``` This configuration will first prefer to put the `loadgen` pods on different nodes from each other, which is important for the fault tolerance of the `loadgen` pods themselves. As a secondary priority, it will attempt to put the pods on nodes that do not already have a running `CockroachDB` pod. This will ensure the best possible balance of fault tolerance and performance for the load generator and CockroachDB cluster. ### Networking [Kubernetes asks a lot of the network that it runs on](https://kubernetes.io/docs/concepts/cluster-administration/networking/) in order to provide a routable IP address and an isolated Linux network namespace to each pod in the cluster, among its other requirements. While this document isn't nearly large enough to properly explain the details, and those details themselves can depend heavily on specifically how you have set up the network for your cluster, it suffices to say that Docker and Kubernetes's networking abstractions often come with a performance penalty for high-throughput distributed applications such as CockroachDB. If you really want to eke more performance out of your cluster, networking is a good target to at least experiment with. You can either replace your cluster's networking solution with a more performant one or bypass most of the networking overhead by using the host machines' networks directly. #### Networking solutions If you aren't using a hosted Kubernetes service, you'll typically have to choose how to set up the network when you're creating a Kubernetes cluster. There are [a lot of solutions out there](https://kubernetes.io/docs/concepts/cluster-administration/networking/#how-to-achieve-this), and they can have significantly different performance characteristics and functionality. We do not endorse any networking software or configurations in particular, but want to call out that your choice can have a meaningful affect on performance compared to running CockroachDB outside of Kubernetes. #### Using the host's network If you are already content with your cluster's networking setup or do not want to have to mess with it, Kubernetes does offer an escape hatch for exceptional cases that lets you avoid network performance overhead -- the `hostNetwork` setting, which allows you to run pods using their host machine's network directly and bypass the layers of abstraction. This comes with a number of downsides, of course. For example, two pods using `hostNetwork` on the same machine cannot use the same ports, and it also can have serious security implications if your machines are reachable on the public Internet. If you want to give it a try, though, to see what effects it has for your workload, you just have to add two lines to the CockroachDB YAML configuration file and to any client applications that desperately need better performance, changing: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: affinity: ``` To be: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: hostNetwork: true dnsPolicy: ClusterFirstWithHostNet affinity: ``` `hostNetwork: true` tells Kubernetes to put the pods in the host machine's network namespace, using its IP address, hostname, and entire networking stack. The `dnsPolicy: ClusterFirstWithHostNet` line tells Kubernetes to configure the pods to still be able to use the cluster's DNS infrastructure for service discovery. This will not work miracles, so use it with caution. In our testing, it pretty reliably gives about a 6% improvement in database throughput when running [our `kv` load generator](https://hub.docker.com/r/cockroachdb/loadgen-kv/) against a 3-node cluster on GKE. ### Running in a DaemonSet A [DaemonSet](https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/) is a Kubernetes resource that runs a pod on all nodes that match some selection criteria. This can be a more natural abstraction for using [dedicated nodes](#dedicated-nodes), and naturally pairs with [using the host's network](#using-the-host’s-network) since it couples CockroachDB processes one-to-one with nodes. > [!CAUTION] > > We strongly recommend **against** using DaemonSets due to their weaker fault tolerance and data survivability capabilities, in comparison to StatefulSets. In most Kubernetes environments, nodes are considered ephemeral. However, a DaemonSet pod ties a CockroachDB node to a specific Kubernetes node, and cannot be rescheduled to another Kubernetes node in the event of an automatic upgrade or hardware failure. Unless you have manually set up persistent volumes, DaemonSet deployments will lose all their data when Kubernetes nodes are replaced in a cluster. > > This limits Kubernetes's ability to help your cluster recover from failures, and matches the behavior of running CockroachDB directly on a set of physical machines that are only manually replaced by human operators. ### Dedicated nodes If your Kubernetes cluster is made up of heterogeneous hardware, it's likely that you'd like to make sure CockroachDB only runs on certain machines. If you want to get as much performance as possible out of a set of machines, you might also want to make sure that only CockroachDB is run on them. For more information, see [Pod scheduling](/docs/v26.4/schedule-cockroachdb-kubernetes). ## See also * [Orchestrate CockroachDB with Kubernetes](/docs/v26.4/deploy-cockroachdb-with-kubernetes) * [Production Checklist](/docs/v26.4/recommended-production-settings) * [SQL Performance Best Practices](/docs/v26.4/performance-best-practices-overview) * [Troubleshooting Performance Issues](/docs/v26.4/query-behavior-troubleshooting) # Configure LDAP Authentication Source: https://docs.cockroachlabs.com/docs/stable/ldap-authentication > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). CockroachDB supports authentication and authorization using systems compatible with the Lightweight Directory Access Protocol (LDAP), such as Active Directory and Microsoft Entra ID. This allows you to integrate your cluster with your organization's existing identity infrastructure for centralized user management and access control. This page describes how to configure CockroachDB user authentication using LDAP. You can additionally configure CockroachDB to use the same directory service for user [authorization](/docs/v26.4/ldap-authorization) (role-based access control), which assigns CockroachDB roles to users based on their group memberships in the directory. For alternative SSO authentication methods, refer to [Single Sign-on (SSO) for DB Console](/docs/v26.4/sso-db-console) (OIDC), [Cluster Single Sign-on (SSO) using JWTs](/docs/v26.4/sso-sql), and [SASL OAUTHBEARER (OAuth 2.0) Authentication for SQL Clients](/docs/v26.4/oauth-authentication). ## Overview LDAP authentication in CockroachDB works with LDAP-compatible directory services, including Microsoft Entra ID, Active Directory, and OpenLDAP. Secure LDAPS connectivity over TLS is required. While LDAP configuration is cluster-specific, each request to authenticate a user in CockroachDB is handled by the node that receives it. When LDAP is enabled, the node handles each authentication request using a "search and bind" approach: 1. Find the user record * The node connects to the LDAP server using a dedicated directory access account. * The node searches the directory for a record that matches the authenticating user, using configurable search criteria. 1. Authenticate the user * If a matching record was found, the cluster attempts to verify the user's identity through another LDAP request, this time using the credentials (username and password) provided by that user. * If this LDAP bind operation succeeds, the user is authenticated to the CockroachDB cluster. 1. Authorize the user (optional) * If [LDAP authorization](/docs/v26.4/ldap-authorization) is also enabled, an additional request is sent to retrieve the groups to which the user is assigned, using configurable criteria. * If group memberships are found, any existing CockroachDB roles that match these group names are assigned to the user. These requests use a node's existing connection to the LDAP server, if one is open. Otherwise, the node establishes a new connection. The connection remains open for handling additional LDAP requests until it is closed by the LDAP server, based on its timeout setting. Because CockroachDB maintains no more than one LDAP connection per node, for a cluster with `n` nodes, you can expect up to `n` concurrent LDAP connections. > [!NOTE] > > LDAP authentication cannot be used for the `root` user or other [reserved identities](/docs/v26.4/security-reference/authorization#reserved-identities). Credentials for `root` must be managed separately using password authentication to ensure continuous administrative access regardless of LDAP availability. ## Configuration ### Prerequisites * An LDAP-compatible directory service, such as Microsoft Entra ID or Active Directory. * Network connectivity on port 636 for LDAPS. * A service account (bind DN) with permissions to search the directory for basic information about users and groups. For example, in Microsoft Entra ID, a [service principal](https://learn.microsoft.com/entra/architecture/secure-service-accounts) with the Directory Readers role. * The LDAP server's CA certificate, if using a custom CA not already trusted by the CockroachDB host. * Verification that the attribute values that will become CockroachDB usernames meet the CockroachDB [requirements for usernames](/docs/v26.4/create-user#user-names). Before you begin, it may be useful to enable authentication logging, which can help you confirm successful configuration or troubleshoot issues. For details, refer to [Troubleshooting](#troubleshooting). ### Step 1: Enable redaction of sensitive cluster settings For this integration, you will need to store LDAP bind credentials for the service account that enables the integration in the [cluster setting `server.host_based_authentication.configuration`](/docs/v26.4/cluster-settings). You will also configure the mapping of external identities to CockroachDB SQL users with the [cluster setting `server.identity_map.configuration`](/docs/v26.4/cluster-settings). In addition, for a custom CA configuration, you may need to store certificate and key details in the cluster settings specified in the optional [Step 3: Configure TLS](#step-3-configure-tls-optional). It is highly recommended that you redact these settings, so that only authorized users, such as members of the `admin` role, can view them. To enable this redaction and learn about its permission scheme, refer to [Sensitive settings](/docs/v26.4/cluster-settings#sensitive-settings). ### Step 2: Configure host-based authentication (HBA) To enable LDAP, you will need to update the [host-based authentication (HBA)](/docs/v26.4/security-reference/authentication#authentication-configuration) configuration specified in the [cluster setting `server.host_based_authentication.configuration`](/docs/v26.4/cluster-settings). Set the authentication method for all users and databases to `ldap` and include the LDAP-specific option parameters: * `ldapserver`: LDAP server hostname * `ldapport`: LDAP server port (typically 636 for LDAPS) * `ldapbasedn`: Base DN for user searches * `ldapbinddn`: Service account DN for directory searches * `ldapbindpasswd`: Service account password * `ldapsearchattribute`: Attribute to match against SQL usernames * `ldapsearchfilter`: LDAP filter to restrict valid users For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.host_based_authentication.configuration = ' host all all all ldap ldapserver=ldap.example.com ldapport=636 "ldapbasedn=ou=users,dc=example,dc=com" "ldapbinddn=cn=readonly,dc=example,dc=com" ldapbindpasswd=readonly_password ldapsearchattribute=uid "ldapsearchfilter=(memberof=cn=cockroachdb_users,ou=groups,dc=example,dc=com)"'; ``` If you also intend to configure LDAP Authorization, you will need to include an additional LDAP parameter, `ldapgrouplistfilter`. For details, refer to [LDAP Authorization](/docs/v26.4/ldap-authorization#configuration). ### Step 3: Configure TLS (Optional) If, for LDAPS, you are using a certificate signed by a custom Certificate Authority (CA) that is not in the system's trusted CA store, you will need to configure the CA certificate. This step is only necessary when using certificates signed by your organization's private CA or other untrusted CA. **Set the custom CA certificate:** ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.ldap_authentication.domain.custom_ca = ''; ``` **Configure a client certificate for mTLS if required:** ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.ldap_authentication.client.tls_certificate = ''; SET CLUSTER SETTING server.ldap_authentication.client.tls_key = ''; ``` ### Step 4: Configure user creation CockroachDB supports two approaches for the creation of users who will authenticate via LDAP: #### Option 1: Automatic user provisioning (recommended) With automatic user provisioning, CockroachDB creates users automatically during their first successful LDAP authentication, whether connecting via a SQL client or the [DB Console](/docs/v26.4/ui-overview). This eliminates the need for custom scripting to create user accounts. When enabled: * Users are created automatically upon successful LDAP authentication. * All auto-provisioned users receive a `PROVISIONSRC` role option set to `ldap:{ldap_server}`. * The `estimated_last_login_time` is tracked for auditing purposes. * Auto-provisioned users cannot change their own passwords (managed via LDAP only). For Active Directory deployments, the CockroachDB username will match the `sAMAccountName` field from the `user` object. Specify this field name with `ldapsearchattribute=sAMAccountName` in the HBA configuration. Ensure that the values in the field you are using for `ldapsearchattribute` meet the CockroachDB [requirements for usernames](/docs/v26.4/create-user#user-names). > [!NOTE] > > Before you enable automatic user provisioning, it is recommended that you enable [LDAP authorization](/docs/v26.4/ldap-authorization). This ensures that upon initial login, new CockroachDB users are members of the intended CockroachDB roles, with the privileges they confer, according to users' group memberships in the directory. Otherwise, functionality may be limited for a new user until your alternative process applies roles or privileges. > > If you choose to manage CockroachDB role memberships and privileges directly, you could script the required [`GRANT`](/docs/v26.4/grant) commands to be [executed](/docs/v26.4/cockroach-sql#general) as needed. **To enable automatic user provisioning:** ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING security.provisioning.ldap.enabled = true; ``` #### Option 2: Manual/scripted user creation Alternatively, you can manage users by directly creating them before LDAP authentication is used. This approach provides explicit control over user creation. To create a single user: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE username LOGIN; ``` To create users in bulk: 1. Export usernames from the directory server. 2. Produce a `.sql` file with a [`CREATE ROLE`](/docs/v26.4/create-role) statement per user, each on a separate line. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE username1 LOGIN; CREATE ROLE username2 LOGIN; CREATE ROLE username3 LOGIN; ``` If you are not also enabling LDAP Authorization to manage roles and privileges, you can also include one or more `GRANT` lines for each user. For example, `GRANT developer TO username1` or `GRANT SELECT ON DATABASE orders TO username2;`. 3. Run the SQL statements in the [file](/docs/v26.4/cockroach-sql#general): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --file=create_users.sql --host= [!TIP] > > When [LDAP authorization](/docs/v26.4/ldap-authorization) is configured (with `ldapgrouplistfilter` in the HBA configuration), role-based access control is applied automatically upon login to both SQL clients and the DB Console. Users logging into the DB Console via LDAP will have their roles synchronized from LDAP groups, just as they are for SQL client connections. ## Manage auto-provisioned users When automatic user provisioning is enabled, you can identify and manage auto-provisioned users using the following methods: ### View provisioned users Auto-provisioned users can be identified by their `PROVISIONSRC` role option using the [`SHOW USERS WITH SOURCE`](/docs/v26.4/show-users) syntax: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- View all LDAP auto-provisioned users SHOW USERS WITH SOURCE = 'ldap:ldap.example.com'; ``` Replace `ldap.example.com` with your LDAP server address. To view manually created users (those without a provisioning source), use the `unnest` query pattern since `WITH SOURCE` cannot express negation: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- View all manually created users (users without PROVISIONSRC role option) SELECT * FROM [SHOW USERS] AS u WHERE NOT EXISTS ( SELECT 1 FROM unnest(u.options) AS opt WHERE opt LIKE 'PROVISIONSRC=ldap:%' ); ``` ### Last-login tracking for usage and dormancy When `security.provisioning.ldap.enabled` is set to `true`, the `estimated_last_login_time` column in the `SHOW USERS` output is updated for both SQL client connections and DB Console authentication attempts. This allows administrators to track user activity across all connection methods and identify dormant accounts, even for users who successfully authenticate but lack privileges to access the DB Console. The `estimated_last_login_time` column in the output of `SHOW USERS` tracks when users last authenticated. For example: ``` username | options | member_of | estimated_last_login_time -----------------+---------------------------------------+-----------+---------------------------- admin | {} | {} | NULL root | {} | {admin} | 2025-06-01 11:51:29.406216+00 e.codd | {PROVISIONSRC=ldap:example.com} | {} | 2025-08-04 19:18:00.201402+00 ``` > [!NOTE] > > `estimated_last_login_time` is computed on a best-effort basis and may not capture every login event due to asynchronous updates. **To identify potentially dormant auto-provisioned users:** ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Find LDAP-provisioned users who haven't logged in for 90 days SHOW USERS WITH SOURCE = 'ldap:ldap.example.com', LAST LOGIN BEFORE NOW() - INTERVAL '90 days'; ``` > [!NOTE] > > [`LAST LOGIN BEFORE`](/docs/v26.4/show-users) excludes users who have never logged in (NULL `estimated_last_login_time`). To find those users separately: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Find LDAP-provisioned users who have never logged in SELECT username, estimated_last_login_time FROM [SHOW USERS WITH SOURCE = 'ldap:ldap.example.com'] WHERE estimated_last_login_time IS NULL; ``` ### Clean up users removed from Active Directory Auto-provisioned users who have been removed or deactivated in Active Directory will not be automatically removed from CockroachDB. To identify and clean up these orphaned accounts: **Step 1: Export auto-provisioned users from CockroachDB** ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Export list of auto-provisioned usernames for comparison with Active Directory SELECT username FROM [SHOW USERS WITH SOURCE = 'ldap:ldap.example.com']; ``` **Step 2: Cross-reference with Active Directory** Use your organization's directory tools to verify which of these users still exist in Active Directory. For example, you might use PowerShell with Active Directory cmdlets: ```powershell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Example PowerShell script to check if users exist in AD $cockroachUsers = @("user1", "user2", "user3") # Replace with actual usernames $orphanedUsers = @() foreach ($user in $cockroachUsers) { try { Get-ADUser -Identity $user -ErrorAction Stop | Out-Null } catch { $orphanedUsers += $user Write-Host "User not found in AD: $user" } } ``` **Step 3: Remove orphaned users** Before dropping users confirmed to no longer exist in Active Directory, check for any privileges that were granted directly to the user: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Check for direct grants to the user (privileges inherited through roles won't block DROP USER) SHOW GRANTS FOR username; ``` If any direct grants exist, revoke them before dropping the user. For a small number of specific users confirmed to no longer exist in Active Directory: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Remove users that no longer exist in Active Directory DROP USER username1, username2, username3; ``` > [!NOTE] > > Users cannot be dropped if they have direct privilege grants or own database objects. For complete requirements, refer to [`DROP USER`](/docs/v26.4/drop-user). When using both automatic user provisioning and LDAP Authorization, consider granting privileges primarily through roles (mapped to AD groups) rather than directly to users to simplify cleanup operations. #### Bulk-drop dormant provisioned users To de-provision auto-provisioned users at scale, use [`DROP PROVISIONED ROLES`](/docs/v26.4/drop-provisioned-roles). This statement drops only auto-provisioned users (users with a [`PROVISIONSRC`](/docs/v26.4/create-user#role-options) role option) that match the specified filters, and automatically skips users that own objects or have other dependencies. A `LIMIT` is required to bound the number of users dropped in a single statement. For example, to drop up to 100 users that were provisioned by a specific LDAP server and have not logged in since a specific date: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} DROP PROVISIONED ROLES WITH SOURCE = 'ldap:ldap.example.com', LAST LOGIN BEFORE '2025-01-01' LIMIT 100; ``` Before dropping users, preview which users match your filters by running [`SHOW USERS`](/docs/v26.4/show-users) with the same clauses: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SHOW USERS WITH SOURCE = 'ldap:ldap.example.com', LAST LOGIN BEFORE '2025-01-01'; ``` Each dropped user is recorded in the [`USER_ADMIN`](/docs/v26.4/logging#user_admin) logging channel for auditing. ### Restrictions on auto-provisioned users Users created through automatic provisioning have specific restrictions: * **Password changes**: Auto-provisioned users cannot change their own passwords using `ALTER USER`, even if the cluster setting `sql.auth.change_own_password.enabled` is true. * **PROVISIONSRC modification**: The `PROVISIONSRC` role option cannot be modified or removed once set. * **Authentication method**: These users must authenticate through OIDC; password-based authentication is not available. Attempting to change the password of an auto-provisioned user will result in an error: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER USER provisioned_user WITH PASSWORD 'newpassword'; ``` ``` ERROR: cannot alter PASSWORD/PROVISIONSRC option for provisioned user provisioned_user ``` ## Troubleshooting Enable [`SESSION` logging](/docs/v26.4/logging#sessions) to preserve data that will help troubleshoot LDAP issues. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.auth_log.sql_sessions.enabled = true; ``` > [!NOTE] > > Once all functionality is configured and tested successfully, we recommend disabling session logging to conserve system resources. To view the logs, open `cockroach-session.log` from your [logging directory](/docs/v26.4/configure-logs#logging-directory). Potential issues to investigate may pertain to: * Network connectivity to the LDAP server. * Incorrect bind DN or password. * Search filter not matching the intended users. * TLS certificates. * Missing or mismatched role names. ## Security considerations 1. Always keep a backup authentication method (like password) for administrative users. 2. Use LDAPS (LDAP over TLS) in production environments. 3. Use a restricted service account for directory searches. 4. Regularly audit LDAP group memberships. 5. Monitor authentication logs for unusual patterns. 6. **Auto-provisioning considerations**: * When enabling automatic user provisioning, ensure your LDAP search filters are restrictive to prevent unauthorized user creation. * Regularly review auto-provisioned users using the `SHOW USERS` command to identify accounts that may need deprovisioning. * If using LDAP Authorization, ensure all group roles are created before enabling auto-provisioning to maintain proper access control. * The `estimated_last_login_time` can help identify dormant accounts that may need manual removal. # Configure LDAP Authorization Source: https://docs.cockroachlabs.com/docs/stable/ldap-authorization > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). If you manage users through a service compatible with the Lightweight Directory Access Protocol (LDAP), such as Active Directory or Microsoft Entra ID, you can configure CockroachDB to automatically assign [roles](/docs/v26.4/security-reference/authorization) to users based on LDAP group memberships, simplifying access control. LDAP authorization applies to both SQL client connections and [DB Console](/docs/v26.4/ui-overview) logins. When a user authenticates via LDAP, their roles are automatically synchronized from LDAP groups, providing consistent role-based access control across all connection methods. If LDAP authorization is enabled: 1. When a client connects to the cluster using LDAP, the cluster looks up the user's group membership in the LDAP service. 2. Each LDAP group is mapped to a cluster role using the group's Common Name (CN) in the LDAP service. 3. The user is granted each corresponding role, and roles that the user holds [directly](/docs/v26.4/security-reference/authorization#direct-member) but that no longer match the user's groups are revoked. Roles the user holds [indirectly](/docs/v26.4/security-reference/authorization#indirect-member) through a directly granted role are not revoked individually; if the LDAP group list names only such a role, the directly granted role is revoked and the named role is granted directly. 4. In conjunction with [automatic user provisioning](/docs/v26.4/ldap-authentication#option-1-automatic-user-provisioning-recommended) if enabled, users are created automatically during their first authentication and simultaneously receive specified role memberships. ## Prerequisites * Enable [LDAP Authentication](/docs/v26.4/ldap-authentication). ## Configuration Before you begin, it may be useful to enable authentication logging, which can help you confirm sucessful configuration or troubleshoot issues. For details, refer to [Troubleshooting](#troubleshooting). ### Step 1: Enable LDAP authorization Add the `ldapgrouplistfilter` parameter to the HBA configuration that you enabled for [LDAP Authentication](/docs/v26.4/ldap-authentication). The configuration will include two important LDAP filters: 1. `ldapsearchfilter`: Determines which users can authenticate 2. `ldapgrouplistfilter`: Defines which groups should be considered for authorization Here's a basic example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.host_based_authentication.configuration = ' host all all all ldap ldapserver=ldap.example.com ldapport=636 "ldapbasedn=ou=users,dc=example,dc=com" "ldapbinddn=cn=readonly,dc=example,dc=com" ldapbindpasswd=readonly_password ldapsearchattribute=uid "ldapsearchfilter=(memberof=cn=cockroachdb_users,ou=groups,dc=example,dc=com)" "ldapgrouplistfilter=(objectClass=groupOfNames)"'; ``` For more precise control, you can configure these filters to match your security requirements. Refer to the examples below, and further documentation on [LDAP syntax filters](https://learn.microsoft.com/en-us/archive/technet-wiki/5392.active-directory-ldap-syntax-filters). #### Search filter examples To restrict authentication to members of specific groups: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Users must be members of either the database users group or the analytics team "ldapsearchfilter=(|(memberof=cn=cockroachdb_users,ou=groups,dc=example,dc=com)(memberof=cn=analytics_team,ou=groups,dc=example,dc=com))" ``` #### Group list filter examples The `ldapgrouplistfilter` configuration varies by LDAP server type: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- For Azure Active Directory: "ldapgrouplistfilter=(objectCategory=CN=Group,CN=Schema,CN=Configuration,DC=example,DC=com)" -- For OpenLDAP: "ldapgrouplistfilter=(objectClass=groupOfNames)" ``` For enhanced security, restrict the groups that can be mapped to CockroachDB roles: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Only map specific groups to CockroachDB roles "ldapgrouplistfilter=(|(cn=crdb_analysts)(cn=crdb_developers))" ``` > [!NOTE] > > We recommend that you explicitly specify which groups should be mapped to CockroachDB roles rather than using broader filters. This ensures that only intended groups are granted database access. ### Step 2: Create matching roles Create CockroachDB roles that match your LDAP group names and grant appropriate privileges to each role. Remember that role names must comply with CockroachDB's [identifier requirements](/docs/v26.4/create-user#user-names). For example, if you've configured the group filter to allow `crdb_analysts` and `crdb_developers`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Create role for analysts CREATE ROLE crdb_analysts; GRANT SELECT ON DATABASE analytics TO crdb_analysts; -- Create role for developers CREATE ROLE crdb_developers; GRANT ALL ON DATABASE app TO crdb_developers; ``` > [!NOTE] > > If you are going to use [automatic user provisioning](/docs/v26.4/ldap-authentication#option-1-automatic-user-provisioning-recommended) in conjunction with LDAP authorization, be sure to complete the creation of group roles before enabling automatic user provisioning. Auto-provisioned users will only receive roles for groups that already exist as CockroachDB roles. ### Step 3: Confirm configuration 1. On the LDAP server, set up test users with memberships in groups that should be synced to CockroachDB users. 2. If [automatic user provisioning](/docs/v26.4/ldap-authentication#option-1-automatic-user-provisioning-recommended) is not enabled, create the matching test users when logged in as an admin to CockroachDB: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE username1 LOGIN; CREATE ROLE username2 LOGIN; CREATE ROLE username3 LOGIN; ``` If automatic user provisioning is enabled, users will be created automatically during their first login. 3. Log in to CockroachDB as each test user (refer to [Connect to a cluster using LDAP](/docs/v26.4/ldap-authentication#connect-to-a-cluster-using-ldap)). 4. Using your `admin` credentials, log in to the CockroachDB SQL shell and run `SHOW USERS;` to view and verify users and their role assignments. For auto-provisioned users, you can identify them by their `PROVISIONSRC` role option using the [`SHOW USERS WITH SOURCE`](/docs/v26.4/show-users) syntax: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- View all users and their role assignments SHOW USERS; -- Filter for LDAP auto-provisioned users SHOW USERS WITH SOURCE = 'ldap:ldap.example.com'; ``` ## Troubleshooting Enable [`SESSION` logging](/docs/v26.4/logging#sessions) to preserve data that will help troubleshoot LDAP issues: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.auth_log.sql_sessions.enabled = true; ``` > [!NOTE] > > Once all functionality is configured and tested successfully, we recommend disabling session logging to conserve system resources. To view the logs, open `cockroach-session.log` from your [logging directory](/docs/v26.4/configure-logs#logging-directory). Potential issues to investigate may pertain to: * Network connectivity to the LDAP server. * Incorrect bind DN or password. * Search filter not matching the intended users. * TLS certificates. * Missing or mismatched role names. ## Security considerations 1. Always keep a backup authentication method (like password) for administrative users. 2. Use LDAPS (LDAP over TLS) in production environments. 3. Use a restricted service account for directory searches. 4. Regularly audit LDAP group memberships. 5. Monitor authentication logs for unusual patterns. # Use the CockroachDB CLI to provision a development cluster Source: https://docs.cockroachlabs.com/docs/stable/manage-certs-cli The CockroachDB CLI's [`cockroach cert`](/docs/v26.4/cockroach-cert) command allows you to generate [private key/public certificate pairs for TLS authentication and encryption](/docs/v26.4/security-reference/transport-layer-security) in communication between CockroachDB nodes, and from SQL clients to the cluster. > [!NOTE] > > The ability to rapidly and locally generate private key/public certificate pairs is important for development, but careful management of security certificates is an essential component of cluster security. We recommend that you use a cloud-native tool, such as Google Cloud Platform's Certificate Authority Service (CAS), to manage security certificates. > > Learn more: [Manage PKI certificates for a CockroachDB deployment with HashiCorp Vault](/docs/v26.4/manage-certs-vault). ## Create the CA certificate and key pair 1. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir my-safe-directory ``` * `certs`: You'll generate your CA certificate and all node and client certificates and keys in this directory and then upload some of the files to your nodes. * `my-safe-directory`: You'll generate your CA key in this directory and then reference the key when generating node and client certificates. Keep the key safe and secret; do not upload it to your nodes. 2. Generate the CA certificate and key: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ls -l certs ``` ``` total 8 -rw-r--r-- 1 maxroach maxroach 1.1K Jul 10 14:12 ca.crt ``` ## Create the certificate and key pairs for nodes 1. Generate the certificate and key for the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ node1.example.com \ node1.another-example.com \ *.dev.another-example.com \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ls -l certs ``` ``` total 24 -rw-r--r-- 1 maxroach maxroach 1.1K Jul 10 14:12 ca.crt -rw-r--r-- 1 maxroach maxroach 1.2K Jul 10 14:16 node.crt -rw------- 1 maxroach maxroach 1.6K Jul 10 14:16 node.key ``` 2. Upload certificates to the first node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Create the certs directory: $ ssh @@ [!NOTE] > > This is necessary because the certificates and keys for additional nodes will also be named `node.crt` and `node.key` As an alternative to deleting these files, you can run the next `cockroach cert create-node` commands with the `--overwrite` flag. 1. Create the certificate and key for the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-node \ node2.example.com \ node2.another-example.com \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ ls -l certs ``` ``` total 24 -rw-r--r-- 1 maxroach maxroach 1.1K Jul 10 14:12 ca.crt -rw-r--r-- 1 maxroach maxroach 1.2K Jul 10 14:17 node.crt -rw------- 1 maxroach maxroach 1.6K Jul 10 14:17 node.key ``` 2. Upload certificates to the second node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Create the certs directory: $ ssh @@ SHOW CLUSTER SETTING security.ocsp.mode; ``` ``` security.ocsp.mode ---------------------- off (1 row) Server Execution Time: 56µs Network Latency: 181µs ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SET CLUSTER SETTING security.ocsp.mode = lax; ``` For production clusters, we recommend that you set `security.ocsp.mode` to `strict`, but only after verifying the configuration with it set to `lax`. > [!NOTE] > > In the `strict` mode, all certificates are presumed to be invalid if the OCSP server is not reachable. Setting the cluster setting `security.ocsp.mode` to `strict` will lock you out of your CockroachDB database if your OCSP server is unavailable. # Manage PKI certificates with HashiCorp Vault Source: https://docs.cockroachlabs.com/docs/stable/manage-certs-vault This tutorial guides the user through implementing [public key infrastructure (PKI)](/docs/v26.4/security-reference/transport-layer-security) for a CockroachDB self-hosted cluster deployed in Google Cloud Platform (GCP), using [Vault PKI Secrets Engine](/docs/v26.4/hashicorp-integration) . PKI involves careful management of the certificates used for authentication and encryption in network traffic between servers and clients. **Goals**: * Deploy a secure three-node CockroachDB cluster in Google Cloud Platform. * Create two certificate authorities (CAs), one each for clients and for cluster nodes * Define PKI roles for CockroachDB nodes and clients * Issue private key/public certificate pairs for use by our CockroachDB cluster nodes * Issue a private key/public certificate pair for use by the CockroachDB client * Access the cluster using the client credentials ## Before you begin * Review [Transport Layer Security (TLS) and Public Key Infrastructure (PKI)](/docs/v26.4/security-reference/transport-layer-security). * Vault: * You must have access to a Vault cluster. This can be a cluster provisioned online through [HashiCorp Cloud Platform (HCP)](https://portal.cloud.hashicorp.com/services/vault), a Vault cluster deployed by your organization, or a quickstart Vault cluster you deploy yourself in ["dev" mode](https://learn.hashicorp.com/tutorials/vault/getting-started-dev-server?in=vault/getting-started). * You need permissions on the Vault cluster to enable secrets engines and create policies, either via the root access token for this cluster or through a [custom policy](https://learn.hashicorp.com/tutorials/vault/policies). * Google Cloud Platform (GCP): * Create a new GCP account and project. * Install and configure the Google Cloud CLI (gcloud) and enable [Google CA Service](https://console.cloud.google.com/security/cas). ## Introduction PKI can be implemented in many ways; key pairs can be generated and certificates signed using many different commands or tools, including OpenSSL, the CockroachDB CLI, or other utilities or services. Similarly, there are multiple ways to safely distribute those credentials to servers and clients. ### PKI strategy The key elements of the strategy here are: * To leverage the strength of Vault's secrets engines to manage the certificates. * To enforce *short validity durations for all issued certificates*, rather than employing the more heavy-weight option of [Online Certificate Status Protocol (OCSP)](/docs/v26.4/manage-certs-revoke-ocsp). This solution uses HashiCorp Vault to manage these credentials as secrets. This approach benefits from Vault's generally strong security model and ease of use. ### Short-lived credentials If credentials are obtained by malicious actors, they can be used to impersonate (spoof) a client or server. Any PKI implementation must prevent this type of impersonation: * By using a revocation mechanism, so that existing certificates can be invalidated. Two standard solutions are Certificate Revocation Lists (CRLS) and the Online Certificate Status Protocol (OCSP). * By issuing only certificates with short validity durations, so that any compromised certificate quickly becomes unusable. CockroachDB OCSP but not CRLs. To learn more, read [Using Online Certificate Status Protocol (OCSP) with CockroachDB](/docs/v26.4/manage-certs-revoke-ocsp). Without OCSP, there is a premium on enforcing short validity durations for certificates; otherwise, stolen credentials may be used to work persistent mischief over a long window. The approach taken here can be automated. Users should consider automating PKI-related operations to reduce latency, repetition, and mistakes. For example, you might choose to issue new certificates daily, and for those certificates to remain valid for two days. ### Task personas The work described here can be divided up into three chunks, each of which might be performed by a different team or individual, and each of which might require access to different resources in both GCP and Vault. Each of the three personas in the following table correspond to a GCP service account and a Vault policy. | persona | tasks | Vault permissions | GCP Permissions | | - | - | - | - | | `ca-admin` |
  • Manage CA lifecycle
  • Issue node certificates
  • Issue client certificates
|
  • Admin
|
  • CA jumpbox access
  • Node SSH access
  • Client SSH access
| | `node-operator` |
  • Install, configure and run CockroachDB and dependencies on nodes
| |
  • Node SSH access
| | `client-operator` |
  • Install, configure and run CockroachDB and dependencies on clients
| |
  • Client SSH access
| ### Resources Our cluster will contain three classes of compute instance: * The CA administrative jumpbox, where sensitive credentials will be handled and secure operations related to certificate authority performed. * Database nodes. These examples use a three-node cluster. * A client, which could represent, in a more realistic scenario, either an operations jumpbox for database administrators, or an application server. Additionally, our project's firewall rules must be configured to allow communication between nodes and from client to nodes. ## Admin operations ### Provision and configure your GCP resources 1. Create the CA admin jumpbox. Specify the ca-admin service account, and grant the `cloud-platform` scope, so that files can be sent with SCP from here to the nodes to be provisioned. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute instances create ca-admin-jumpbox \ --scopes "https://www.googleapis.com/auth/cloud-platform" ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/ca-admin-jumpbox]. NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS ca-admin-jumpbox us-central1-a n1-standard-1 10.128.0.59 35.184.145.196 RUNNING ``` 2. Configure cluster firewall rules. Our rules will allow nodes to send requests to each other, and to receive requests from clients (as specified with tags). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute firewall-rules create roach-talk \ --direction ingress \ --action allow \ --source-tags roach-node,roach-client \ --target-tags roach-node \ --rules TCP:26257,TCP:8080 ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Creating firewall...done. NAME NETWORK DIRECTION PRIORITY ALLOW DENY DISABLED roach-talk default INGRESS 1000 tcp:26257,tcp:8080 False ``` 3. Create node instances Create three compute instances to use as CockroachDB nodes. Follow the guidelines described in [Deploy CockroachDB on Google Cloud Platform](/docs/v26.4/deploy-cockroachdb-on-google-cloud-platform#step-2-create-instances), and additionally, specify the `node-operator` service account as the managing service account. Here we add the network tag 'roach-node', which will allow our firewall rule to apply to the nodes instances. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute instances create roach-node-1 \ --machine-type=n2-standard-2 \ --network-interface=network-tier=PREMIUM,subnet=default \ --scopes=https://www.googleapis.com/auth/cloud-platform \ --tags=roach-node gcloud compute instances create roach-node-2 \ --machine-type=n2-standard-2 --network-interface=network-tier=PREMIUM,subnet=default \ --scopes=https://www.googleapis.com/auth/cloud-platform \ --tags=roach-node gcloud compute instances create roach-node-3 \ --machine-type=n2-standard-2 --network-interface=network-tier=PREMIUM,subnet=default \ --scopes=https://www.googleapis.com/auth/cloud-platform \ --tags=roach-node ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/roach-node-1]. Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/roach-node-2]. Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/roach-node-3]. ``` 4. Create the client instance. Here we add the network tag 'roach-client', which will allow our the client to reach the nodes, according to our firewall rule. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute instances create roach-client \ --scopes "https://www.googleapis.com/auth/cloud-platform" \ --tags=roach-client ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/roach-node-1]. NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS roach-node-1 us-central1-a n2-standard-2 10.128.0.3 34.134.11.238 RUNNING Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/roach-node-2]. NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS roach-node-2 us-central1-a n2-standard-2 10.128.0.4 34.136.190.120 RUNNING Created [https://www.googleapis.com/compute/v1/projects/pki-docs-test1/zones/us-central1-a/instances/roach-node-3]. NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS roach-node-3 us-central1-a n2-standard-2 10.128.0.5 34.170.109.109 RUNNING ``` 5. Create or designate a load balancer endpoint. You can do this either by creating a TCP load balancer with a static IP address, or, as a short-cut in development, by simply designating one of the nodes as your load balancer: * Option 1: Create a TCP load balancer. Visit the load balancer page in the GCP console, and create a TCP load balancer, selecting your node instances as targets for a new back-end service, and reserving a static IP address for your front-end service. This IP address will serve as the load balancer IP, `lb_ip`, in the configuration manifest in the following step. * Option 2: Use one of the nodes as a load balancer. Any node in a CockroachDB cluster handle SQL requests, which includes load-balancing work across nodes in the cluster. As a development mode short, cut, simply use the `INTERNAL_IP` for one of your nodes as `lb_ip` in the configuration manifest in the following step. 1. Compile an environment manifest Collect the network names and IP addresses of the resources, which you should be able to glean from the output of `gcloud compute instances list`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute instances list ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS ca-admin-jumpbox us-central1-a n1-standard-1 10.128.0.2 34.70.101.145 RUNNING roach-client us-central1-a n1-standard-1 10.128.0.6 34.134.58.108 RUNNING roach-node-1 us-central1-a n2-standard-2 10.128.0.3 34.134.11.238 RUNNING roach-node-2 us-central1-a n2-standard-2 10.128.0.4 34.136.190.120 RUNNING roach-node-3 us-central1-a n2-standard-2 10.128.0.5 34.170.109.109 RUNNING ``` For ease of use, save the required information in a file, for example called `cockroach-cluster.env`. Then initialize your shell by pasting in the contents or running `source cockroach-cluster.env`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # replace with your project ID export PROJECT_ID=pki-docs-test1 # replace with your cluster's load-balancer IP. export lb_ip=35.238.8.215 # replace with your compute instance names and *internal* IP addresses export node1name=roach-node-1 export node1addr=10.128.0.3 export node2name=roach-node-2 export node2addr=10.128.0.4 export node3name=roach-node-3 export node3addr=10.128.0.5 export client_addr=10.128.0.6 ``` ### Provision the certificate authorities (CAs) with Vault The operations in this section are performed by the`ca-admin` persona, and therefore require admin Vault access and SSH access to the CA admin jumpbox. #### Step 1: Access and prepare the CA admin jumpbox 1. Connect to the CA admin jumpbox using SSH. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute ssh ca-admin-jumpbox ``` 2. Initialize your shell inside the jumpbox with your cluster information by running the contents of your `cockroach-cluster.env` file. 3. Create a secrets directory on the jumpbox. We need somewhere to put key and certificate files while we work. By working on the secure CA jumpbox, which can be carefully gated behind IAM policies controlling SSH access, we minimize the risk of leaking a sensitive credential. Remember that credentials can be leaked other ways, such as by printing out a private key or plain-text password to your terminal in a public place where a camera is pointed at your laptop's screen. Public certificates are less sensitive if they leak, but private keys for nodes and clients are critical secrets and must be managed with extreme care. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cd ~ export secrets_dir="secrets" # replace with desired path to secrets directory mkdir "${secrets_dir}" mkdir "${secrets_dir}/certs" mkdir -p "${secrets_dir}/node1/certs" mkdir -p "${secrets_dir}/node2/certs" mkdir -p "${secrets_dir}/node3/certs" mkdir -p "${secrets_dir}/clients/certs" ``` 4. [Install Vault](https://learn.hashicorp.com/tutorials/vault/getting-started-install) on the jumpbox, following the [instructions for **Ubuntu/Debian** Linux](https://www.vaultproject.io/downloads). 5. Obtain the required parameters to target and authenticate to Vault. 1. Option 1: If using HashiCorp Cloud Platform (HCP): 1. Go to the [HCP console](https://portal.cloud.hashicorp.com), choose Vault from the **Services** menu and then select your cluster. 2. Find the **Public Cluster URL** for your Vault cluster. This will be set as the `VAULT_ADDR` environment variable, in the following step. 3. Generate an admin token by clicking **Generate token**. This will be set as the `VAULT_TOKEN` environment variable, in the following step. 2. Option 2: If using a Vault deployment internal to your organization, contact your Vault administrator for a token and the appropriate endpoint. 3. Option 3: If using a development Vault server (*suitable only for tutorial/testing purposes*), start the Vault development server and obtain credentials locally on your CA admin jumpbox by running `vault server --dev`. 6. Initialize your shell for Vault on the jumpbox ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export VAULT_ADDR= # your Vault cluster's Public URL export VAULT_TOKEN= # your Vault token export VAULT_NAMESPACE="admin" ``` 7. Authenticate with the admin token: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault login $VAULT_TOKEN ``` #### Step 2. Create the certificate authority 1. Create one PKI secrets engine to serve as your cluster CA, and another to serve as your client CA. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault secrets enable -path=cockroach_cluster_ca pki vault secrets enable -path=cockroach_client_ca pki ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Success! Enabled the pki secrets engine at: cockroach_cluster_ca/ Success! Enabled the pki secrets engine at: cockroach_client_ca/ ``` 2. Set a maximum validity duration for certificates signed by your CAs. In this example this maximum duration is 48 hours, appropriate for a scenario where the certificates are provisioned each day, with another 24 hours grace period. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault secrets tune -max-lease-ttl=1000h cockroach_cluster_ca vault secrets tune -max-lease-ttl=1000h cockroach_client_ca ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Success! Tuned the secrets engine at: cockroach_cluster_ca/ Success! Tuned the secrets engine at: cockroach_client_ca/ ``` 3. Generate a root credential pair for each CA. Certificates created with this CA/secrets engine will be signed with the private key generated here. The CA private key cannot be exported from Vault. This safeguards it from being leaked and used to issue fraudulent certificates. The CA public certificate is downloaded in the resulting JSON payload. In a following step, we'll add both CA public certificate to each node's trust store (`cert` directory) so it can be used by the nodes to authenticate the client. The client will also need the cluster CA public certificate in order to authenticate the cluster. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault write \ cockroach_cluster_ca/root/generate/internal \ ttl=1000h \ --format=json > "${secrets_dir}/certs/cockroach_cluster_ca.json" vault write \ cockroach_client_ca/root/generate/internal \ ttl=1000h \ --format=json > "${secrets_dir}/certs/cockroach_client_ca.json" ``` 4. Parse the CA's public certificate from the corresponding JSON payload. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} echo -e $(cat "${secrets_dir}/certs/cockroach_cluster_ca.json" | jq .data.certificate | tr -d '"') > "${secrets_dir}/certs/ca.crt" echo -e $(cat "${secrets_dir}/certs/cockroach_client_ca.json" | jq .data.certificate | tr -d '"') > "${secrets_dir}/certs/ca-client.crt" ``` 5. Copy the public certificate for the cluster CA to the directory intended to populate the trust store for each node, and for the client. This is necessary because the nodes, as well as external clients, act as clients and must authenticate the server. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cp "${secrets_dir}/certs/ca.crt" "${secrets_dir}/node1/certs" cp "${secrets_dir}/certs/ca.crt" "${secrets_dir}/node2/certs" cp "${secrets_dir}/certs/ca.crt" "${secrets_dir}/node3/certs" cp "${secrets_dir}/certs/ca.crt" "${secrets_dir}/clients/certs" ``` 6. Copy the public certificate for the client CA to the directory intended to populate the trust store for each node, so that each node can authenticate the client. The client does not need the client CA public certificate in its trust store. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cp "${secrets_dir}/certs/ca-client.crt" "${secrets_dir}/node1/certs" cp "${secrets_dir}/certs/ca-client.crt" "${secrets_dir}/node2/certs" cp "${secrets_dir}/certs/ca-client.crt" "${secrets_dir}/node3/certs" ``` 7. (Optional) Use `openssl` to examine each certificate, confirming that it has been generated and copied correctly. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # for example... openssl x509 -in "${secrets_dir}/node1/ca.crt" -text | less ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Certificate: Data: Version: 3 (0x2) Serial Number: 1a:72:ac:49:e9:38:38:65:e3:40:16:a8:48:6e:34:a0:3f:0f:00:96 Signature Algorithm: sha256WithRSAEncryption Issuer: Validity Not Before: Jun 21 17:24:39 2022 GMT Not After : Jul 23 17:25:09 2022 GMT Subject: Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) ... ``` ### Create PKI roles and issue certificates for the nodes In Vault, a PKI role is a template for a certificate. 1. Create a node role. The role will be used to generate certificates for the all cluster nodes. Note that certificate attributes must be provided with Vault's specific parameter syntax, which is documented here: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault write "cockroach_cluster_ca/roles/node" \ allow_any_name=true \ client_flag=true \ server_flag=true \ allow_ip_sans=true \ allow_localhost=true \ max_ttl=48h ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Success! Data written to: cockroach_cluster_ca/roles/node ``` 2. Issue a certificate pair for each node. Each certificate is tailored to the node: * The extended key usages attribute `ext_key_usage` must include both server and client auth usages; this is because nodes must frequently initiate requests to other nodes in order to maintain cluster synchrony and load-balance work. * The Subject Alternative Name (SAN) - IP addresses field contains: * the IP address of the node on the internal network of your GCP project (so the node can serve at that address locally, to other nodes). * the IP address of your cluster on the external, public internet (so the node can serve at that address publicly, to application servers). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault write cockroach_cluster_ca/issue/node \ common_name="node" \ alt_names="roachnode1,localhost,node" \ ip_sans="${node1addr},${lb_ip}" \ max_ttl=48h \ --format=json > "${secrets_dir}/node1/certs.json" vault write cockroach_cluster_ca/issue/node \ common_name="node" \ alt_names="${node2name},localhost,node" \ ip_sans="${node2addr},${lb_ip}" \ max_ttl=48h \ --format=json > "${secrets_dir}/node2/certs.json" vault write cockroach_cluster_ca/issue/node \ common_name="node" \ alt_names="${node3name},localhost,node" \ ip_sans="${node3addr},${lb_ip}" \ max_ttl=48h \ --format=json > "${secrets_dir}/node3/certs.json" ``` 3. Parse the key and certificate pair from each return payload. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} echo -e $(cat "${secrets_dir}/node1/certs.json" | jq .data.private_key | tr -d '"') > "${secrets_dir}/node1/node.key" echo -e $(cat "${secrets_dir}/node1/certs.json" | jq .data.certificate | tr -d '"') > "${secrets_dir}/node1/node.crt" echo -e $(cat "${secrets_dir}/node2/certs.json" | jq .data.private_key | tr -d '"') > "${secrets_dir}/node2/node.key" echo -e $(cat "${secrets_dir}/node2/certs.json" | jq .data.certificate | tr -d '"') > "${secrets_dir}/node2/node.crt" echo -e $(cat "${secrets_dir}/node3/certs.json" | jq .data.private_key | tr -d '"') > "${secrets_dir}/node3/node.key" echo -e $(cat "${secrets_dir}/node3/certs.json" | jq .data.certificate | tr -d '"') > "${secrets_dir}/node3/node.crt" ``` 4. Set key file permissions. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} chmod 0600 ${secrets_dir}/*/node.key chown $USER ${secrets_dir}/*/node.key ``` ### Provision each node's credentials and [trust store](/docs/v26.4/security-reference/transport-layer-security#trust-store) 1. Clear any existing certs from each node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute ssh $node1name --command 'rm -rf ~/certs' gcloud compute ssh $node2name --command 'rm -rf ~/certs' gcloud compute ssh $node3name --command 'rm -rf ~/certs' ``` 2. Use SCP to propagate the CA crt and corresponding key pair to each node ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute scp --recurse "${secrets_dir}/node1/certs" $node1name:~ gcloud compute scp --recurse "${secrets_dir}/node2/certs" $node2name:~ gcloud compute scp --recurse "${secrets_dir}/node3/certs" $node3name:~ ``` ### Create a role and issue credentials for the client #### Create a PKI role for the root Issue a root client certificate Generate a private key/public certificate pair for the root SQL user. 1. Generate the client role: ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault write cockroach_client_ca/roles/client \ allow_any_name=true \ client_flag=true \ enforce_hostnames=false \ allow_ip_sans=false \ allow_localhost=false \ max_ttl=48h ``` 2. Use the client role to create credentials (a private key and public certificate) for a root client. CockroachDB takes the name of the SQL user to be authenticated from the `common_name` field. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} vault write "cockroach_client_ca/issue/client" \ common_name=root \ --format=json > "${secrets_dir}/clients/certs.json" ``` 3. Parse the client key and certificate pair from the payload. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} echo -e $(cat "${secrets_dir}/clients/certs.json" | jq .data.private_key | tr -d '"') > "${secrets_dir}/clients/client.root.key" echo -e $(cat "${secrets_dir}/clients/certs.json" | jq .data.certificate | tr -d '"') > "${secrets_dir}/clients/client.root.crt" ``` 4. Set key file permissions. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} chmod 0600 ${secrets_dir}/*/node.key chown $USER ${secrets_dir}/*/node.key ``` ### Provision the client's credentials and trust store 1. Clear any existing credentials and certs: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute ssh roach-client --command 'rm -rf ~/certs' ``` 2. Use SCP to propagate the CA crt and corresponding key pair to each node ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute scp --recurse "${secrets_dir}/clients/certs" roach-client:"~" ``` ### Clean up the CA admin jumpbox Be sure to delete the credential pairs for the nodes and client. You do not need to delete the public certificates for the CAs, as this is not sensitive data. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} rm -r ${secrets_dir}/node1 rm -r ${secrets_dir}/node2 rm -r ${secrets_dir}/node3 rm -r ${secrets_dir}/clients ``` ## Cluster operations ### Install CockroachDB on each node and client Download the CockroachDB executable from `binaries.cockroachdb.com`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} function install_roach_on_node { gcloud compute ssh $1 --command 'if [[ ! -e cockroach-.linux-amd64 ]]; then echo "roach not installed; installing roach" sudo curl https://binaries.cockroachdb.com/cockroach-.linux-amd64.tgz | tar -xz sudo cp -i cockroach-.linux-amd64/cockroach /usr/local/bin/ sudo mkdir -p /usr/local/lib/cockroach sudo cp -i cockroach-.linux-amd64/lib/libgeos.so /usr/local/lib/cockroach/ sudo cp -i cockroach-.linux-amd64/lib/libgeos_c.so /usr/local/lib/cockroach/ else echo "roach already installed" fi' } install_roach_on_node $node1name install_roach_on_node $node2name install_roach_on_node $node3name install_roach_on_node roach-client ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} roach not installed; installing roach roach not installed; installing roach roach not installed; installing roach roach not installed; installing roach ``` ### Start or reset the cluster #### Generate and provision a start script for each node Note that each start script is node specific, configuring each node to advertise its own IP address to the cluster, and attempt to `join` a specified list of peers at specific IP addresses. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # for node 1 cat <<~script~ > start_roach.sh cockroach start \ --certs-dir=certs \ --advertise-addr="${node1addr}" \ --join="${node1addr},${node2addr},${node3addr}" \ --cache=.25 \ --max-sql-memory=.25 ~script~ chmod +x start_roach.sh gcloud compute scp ./start_roach.sh $node1name:~ # for node 2 cat <<~script~ > start_roach.sh cockroach start \ --certs-dir=certs \ --advertise-addr="${node2addr}" \ --join="${node1addr},${node2addr},${node3addr}" \ --cache=.25 \ --max-sql-memory=.25 ~script~ chmod +x start_roach.sh gcloud compute scp ./start_roach.sh $node2name:~ # for node 3 cat <<~script~ > start_roach.sh cockroach start \ --certs-dir=certs \ --advertise-addr="${node3addr}" \ --join="${node1addr},${node2addr},${node3addr}" \ --cache=.25 \ --max-sql-memory=.25 ~script~ chmod +x start_roach.sh gcloud compute scp ./start_roach.sh $node3name:~ ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} start_roach.sh 100% 156 3.0KB/s 00:00 start_roach.sh 100% 156 3.0KB/s 00:00 start_roach.sh 100% 156 3.1KB/s 00:00 ``` #### Start the nodes To start the cluster, execute the pre-provisioned start script. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud beta compute ssh --command './start_roach.sh' "${node1name}" gcloud beta compute ssh --command './start_roach.sh' "${node2name}" gcloud beta compute ssh --command './start_roach.sh' "${node3name}" ``` #### Reset the nodes To start using the new credentials on a running cluster, send a `SIGHUP` signal to each node. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud beta compute ssh "$node1name" --command 'pkill -SIGHUP -x cockroach' gcloud beta compute ssh "$node2name" --command 'pkill -SIGHUP -x cockroach' gcloud beta compute ssh "$node3name" --command 'pkill -SIGHUP -x cockroach' ``` ## Client operations SSH onto the client. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} gcloud compute ssh roach-client ``` ### Initialize the cluster ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach init --certs-dir=certs $lb_ip ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Cluster successfully initialized ``` ### Access the cluster ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --certs-dir=certs --host=$node1addr ``` ```txt theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Welcome to the CockroachDB SQL shell. # All statements must be terminated by a semicolon. # To exit, type: \q. ``` Congratulations, you have deployed a cluster and connected using securely provisioned certificates! # Manual Deployment Source: https://docs.cockroachlabs.com/docs/stable/manual-deployment Use the following guides to deploy CockroachDB manually on-premises or on popular cloud platforms: * [On-Premises](/docs/v26.4/deploy-cockroachdb-on-premises) * [Amazon Web Services (AWS)](/docs/v26.4/deploy-cockroachdb-on-aws) * [Digital Ocean](/docs/v26.4/deploy-cockroachdb-on-digital-ocean) * [Google Cloud Platform (GCE)](/docs/v26.4/deploy-cockroachdb-on-google-cloud-platform) * [Microsoft Azure](/docs/v26.4/deploy-cockroachdb-on-microsoft-azure) ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Migrate from Helm StatefulSet Source: https://docs.cockroachlabs.com/docs/stable/migrate-cockroachdb-kubernetes-helm This guide covers the automatic migration of a CockroachDB cluster managed via a Helm StatefulSet to the CockroachDB Operator. The CockroachDB Operator's migration controller handles the complex logic of migrating nodes, certificates, and resources automatically, ensuring a seamless transition with minimal manual intervention. These instructions assume that you are migrating from a StatefulSet cluster that was configured using the Helm chart with the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade --install --set operator.enabled=false crdb-test --debug ./cockroachdb ``` > [!TIP] > > If your existing cluster was created using the Public operator, refer to the [Public operator migration guide](/docs/v26.4/migrate-cockroachdb-kubernetes-operator). ## Compatibility Before starting migration, verify your cluster configuration is supported by the migration controller: | Feature | Supported | Notes | | - | - | - | | Self-signer certs (Helm built-in) | Yes | Regenerated with join service DNS SANs; originals preserved | | `cert-manager` certs | Yes | Certificate CR updated with join service DNS SANs; issuer references preserved | | User-provided certs (`tls.certs.provided`) | Yes | `CrdbNode` pods mount user's secrets directly; cert regeneration skipped (see [before you begin](#before-you-begin)) | | Insecure clusters (TLS disabled) | Yes | Detected from `--insecure` flag; cert migration phase skipped entirely | | [WAL failover (dedicated PVC)](/docs/v26.4/wal-failover) | Yes | Detected from `failover*` VolumeClaimTemplate and `--wal-failover` flag | | Dedicated logs PVC (`logsdir` / `logs-dir`) | Yes | VolumeClaimTemplate and mount path preserved as LogsStore | | PCR (virtualized/standby) | Yes | Detected from `{name}-init` Job args (`--virtualized`, `--virtualized-empty`) | | Custom service account | Yes | Preserved with `create: false` | | Custom start flags | Partial | Known operator-managed flags (`--join`, `--listen-addr`, `--certs-dir`, etc.) are excluded; all others preserved in `startFlags.upsert` | | [Multi-region](/docs/v26.4/multiregion-overview) | Yes | Requires `migration-regions` annotation with all regions before starting | | Ingress (UI/SQL) | **Partial** | Existing ingress continues working during migration (service names preserved). Config saved as annotation for reference. Ingress resources themselves are not created or modified. Manual Helm adoption required | | ServiceMonitor / PodMonitor | **No** | Not handled by migration. Must be recreated manually after migration to match new pod labels | | NetworkPolicy | **No** | Must be recreated manually if present | | Log-config Secret | Yes | Automatically converted to ConfigMap (operator uses ConfigMaps, Helm uses Secrets) | ## Before you begin Verify the following before starting migration: * CockroachDB cluster is managed by a Helm StatefulSet (not the public operator). * All StatefulSet pods are Running and Ready with no pending rolling updates, scale operations, or evictions. * `kubectl` and `helm` are installed and configured with access to the target cluster. * For multi-region clusters: cloud region and provider labels are applied to K8s nodes. * For multi-region clusters: `migration-regions` annotation is prepared with the full topology. * You have reviewed the [Compatibility](#compatibility) table and confirmed your configuration is supported, or otherwise are prepared to manually recreate unsupported feature configurations. * **If using `tls.certs.provided` (user-provided certs)**: Your certificates include join service DNS SANs (`{cluster-name}-join`, `{cluster-name}-join.{namespace}`, `{cluster-name}-join.{namespace}.svc.cluster.local`). The controller cannot regenerate certificates when the CA private key is not available. * **If using `tls.certs.provided` with `tls.certs.tlsSecret: false`**: Secrets are re-keyed to use Kubernetes TLS convention (`tls.crt`, `tls.key`, `ca.crt`) instead of cockroach-native key names (`node.crt`, `node.key`). The operator expects TLS secrets in the standard Kubernetes format. This is not needed for self-signer or cert-manager modes. ## Migration controller overview The following sections describe how the automated migration controller handles a migration from Helm StatefulSets to the CockroachDB operator: ### What the migration controller does automatically * Detects cert-manager, self-signer, or user-provided certificates. Self-signer and cert-manager certs are regenerated with join service DNS SANs automatically. User-provided certs are mounted directly (regeneration skipped). * Creates RBAC resources (ServiceAccount, Role, RoleBinding, ClusterRole, ClusterRoleBinding) with namespace-qualified names for cluster-scoped resources. * Deletes old PDB and creates a new one during finalization (no protection gap because the new PDB is created immediately after old PDB deletion). * Updates service selectors during migration and restores them on rollback. * Migrates nodes one at a time (highest index first), verifying cluster health between each node. * Detects and preserves Ingress configuration as an annotation on the CrdbCluster. * Migrates `logsdir` / `logs-dir` VolumeClaimTemplate to CrdbNode LogsStore. * Converts log-config Secret to ConfigMap (Helm uses Secrets, operator uses ConfigMaps). * Detects [Physical Cluster Replication (PCR)](/docs/v26.4/physical-cluster-replication-overview) configuration from init jobs. * Detects [WAL failover](/docs/v26.4/wal-failover) configuration from VolumeClaimTemplates and `--wal-failover` flag. ### What requires manual action * Cloud region and provider node labels must be applied before deploying the operator. * The StatefulSet must be manually deleted after finalization to complete migration. * Helm adoption annotations must be applied to all resources post-migration. * Old bare-named ClusterRole/ClusterRoleBinding must be deleted post-migration. * Ingress resources are not annotated for Helm adoption (manual step required). * ServiceMonitor / PodMonitor resources must be recreated with updated pod labels. ### Migration phases A migration using the controller is performed in the following phases: ``` Init -> CertMigration -> PodMigration -> Finalization -> (user deletes STS) -> Complete ``` | Phase | Duration (approx.) | What happens | | - | - | - | | Init | Seconds | Validates prerequisites, creates "v1beta1" `CrdbCluster`, records original replica count | | CertMigration | Seconds to minutes | Detects cert type, regenerates certs with join service SANs, creates CA `ConfigMap`, labels existing pods | | PodMigration | \~5-15 min per node | Creates `CrdbNode`, waits for health, scales down statefulset (STS) by one. Repeats for each node (highest index first) | | Finalization | Seconds | Sets cluster spec (regions, TLS, resources), deletes old PDB, creates new PDB | | Complete | Seconds (after user deletes STS) | Records completion, sets `Mode=MutableOnly`, updates migration label to `complete` | ### Controlling migration (Stop / Resume / Rollback) The following section describe how to safely manage an in-progress migration. #### Stop (Pause) Pauses migration at the current phase. No resources are deleted. CrdbNodes already created remain running and serving traffic. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label sts $STS_NAME crdb.io/migrate=stop --overwrite -n $NAMESPACE ``` #### Resume There is no separate "resume" label value. Use `start` again to resume from the paused phase. The controller detects the `PhaseStopped` state internally and resumes at the correct phase based on how many nodes have already been migrated. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label sts $STS_NAME crdb.io/migrate=start --overwrite -n $NAMESPACE ``` #### Stop during rollback If rollback is in progress and you apply the stop label, the controller pauses the rollback. The status message indicates that migration was stopped while in `RollbackInProgress`. To resume the rollback: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label sts $STS_NAME crdb.io/migrate=rollback --overwrite -n $NAMESPACE ``` To resume forward migration instead: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label sts $STS_NAME crdb.io/migrate=start --overwrite -n $NAMESPACE ``` `start` resumes forward migration, while `rollback` resumes rollback. #### Gap detection on stop If stop is requested between scaling down the StatefulSet and creating the replacement CrdbNode, the controller detects the gap and scales the StatefulSet back up before entering `PhaseStopped`. This keeps every ordinal represented by either a StatefulSet pod or a CrdbNode pod while migration is paused. #### Rollback Rollback is safe at any phase before Complete. Removing the label triggers automatic rollback. The controller automatically: 1. Deletes all CrdbNodes and waits for their pods to terminate. 2. Restores StatefulSet to original replica count. 3. Removes migration labels (`crdb.cockroachlabs.com/cluster`, `svc`) from pods. 4. Deletes CA ConfigMap (`{name}-ca-crt`). 5. Deletes the ConfigMap created from the log-config Secret. 6. Deletes all PDB variants (`{name}`, `{name}-budget`, `{name}-pdb`). 7. Restores original service selectors (`app.kubernetes.io/instance`, `app.kubernetes.io/name`). 8. Deletes namespace-qualified ClusterRole and ClusterRoleBinding (`{namespace}-{name}`). 9. Removes the migration label from the StatefulSet. All cleanup steps are non-fatal. If a resource is already deleted or inaccessible, the controller logs a warning and continues with the remaining cleanup. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label sts $STS_NAME crdb.io/migrate- -n $NAMESPACE ``` **What happens to data during rollback?** Data written during migration is safe. CockroachDB replicates data across nodes. When CrdbNodes are deleted, their data is re-replicated to the remaining STS pods (which are scaled back up). No data is lost as long as the replication factor is maintained. **During rollback, two sets of pods may briefly coexist.** The controller scales the STS back up before deleting CrdbNodes, ensuring the cluster always has enough replicas. **What happens to PVCs during rollback?** When CrdbNodes are deleted, their PVCs are also deleted. When the StatefulSet scales back up, Kubernetes creates new PVCs. Unlike forward migration (which reuses existing PVCs), rollback creates fresh storage. Data safety is maintained through CockroachDB's built-in replication. Data is re-replicated from the nodes that remain healthy throughout the process. #### Rollback safety by phase | Phase | Rollback safe? | Notes | | - | - | - | | Init | Yes | Only a CrdbCluster has been created; no pods affected | | CertMigration | Yes | Only cert secrets created; no pods affected | | PodMigration | Yes | Controller deletes CrdbNodes and scales STS back up | | Finalization | Conditional | Safe if STS still exists. If STS was already deleted, rollback sets `PhaseFailed` | | Complete | No | STS has been deleted. Manual recovery required | #### Label values reference | Label Value | Who Sets It | Meaning | | - | - | - | | `start` | User | Begin or resume migration | | `stop` | User | Pause migration | | `rollback` | User | Request rollback (same as removing label) | | `in-progress` | Controller | Migration is actively running | | `stopped` | Controller | Migration is paused | | `complete` | Controller | Migration finished successfully | | `failed` | Controller | Migration hit an unrecoverable error | | (removed) | User | Triggers rollback | #### Rollback after complete Once `Phase=Complete`, automated rollback is not possible. The StatefulSet has been deleted. Manual recovery steps: 1. Delete all CrdbNodes 2. Manually recreate the StatefulSet with original spec 3. Scale up and verify cluster health 4. Remove the migration label ### Certificate detection The controller automatically detects your certificate method. No manual configuration is needed. * **cert-manager**: If cert-manager Certificate CRs exist for the cluster (`{name}-node`), the controller updates the Certificate CR with join service DNS SANs and preserves the issuer references. cert-manager then regenerates the secrets automatically. CrdbNode pods mount from the cert-manager-managed secret (the name from `spec.secretName` in the Certificate CR), not `{name}-node-secret`. This keeps cert-manager's automatic rotation working after migration. * **Self-signer** (Helm built-in): The controller loads the existing CA from cluster secrets, regenerates node and client certificates with join service DNS SANs, and writes them to the destination secrets (`{name}-node-secret`, `{name}-client-secret`). CrdbNode pods mount from `{name}-node-secret`. The regenerated certificates have a 1-year TTL and are stored as `ExternalCertificates` in the v1beta1 spec. The operator does not auto-rotate `ExternalCertificates`, so after migration you should switch to `cockroachdb.tls.selfSigner.enabled: true` via Helm adoption to enable automatic rotation. If you delay this step, the certs will expire silently after one year. * **Provided certs** (`tls.certs.provided`): The CA private key is not available, so the controller skips cert regeneration. CrdbNode pods mount the user's existing secrets directly (the secret name parsed from the StatefulSet volumes). The user must update their certificates to include join service DNS SANs before starting the migration (see [before you begin](#before-you-begin)). * **Insecure clusters**: Detected from the `--insecure` start flag. The entire cert migration phase is skipped. An `InsecureClusterMigration` warning event is emitted. > [!NOTE] > > Regardless of the original cert type, after migration all certificate secret names are stored as `ExternalCertificates` on the CrdbNode spec. This is the internal representation used by the operator to mount the correct secrets into pods. ## Step 1: Export environment variables Export the following environment variables based on your existing deployment: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # STS_NAME is the CockroachDB StatefulSet deployed via Helm chart. export STS_NAME="crdb-test-cockroachdb" # NAMESPACE is the namespace where the StatefulSet is installed. export NAMESPACE="default" # RELEASE_NAME is the Helm release name. export RELEASE_NAME=$(kubectl get sts $STS_NAME -n $NAMESPACE \ -o jsonpath='{.metadata.annotations.meta\.helm\.sh/release-name}') ``` ## Step 2: Apply cloud region and provider labels (multi-region only) CockroachDB uses K8s node labels for locality-based pod placement. These labels must exist on the nodes before the operator starts scheduling pods. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # AWS kubectl label node {node-name} \ topology.kubernetes.io/region=us-east-1 \ topology.kubernetes.io/zone=us-east-1a \ cockroach.io/cloud=aws # GCP kubectl label node {node-name} \ topology.kubernetes.io/region=us-central1 \ topology.kubernetes.io/zone=us-central1-a \ cockroach.io/cloud=gcp # Azure kubectl label node {node-name} \ topology.kubernetes.io/region=eastus \ topology.kubernetes.io/zone=eastus-1 \ cockroach.io/cloud=azure ``` If the required labels are missing, `CrdbNode` pods will remain `Pending` with scheduling errors. For multi-region clusters, annotate the StatefulSet with the full topology before starting migration: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl annotate sts $STS_NAME \ 'crdb.cockroachlabs.com/migration-regions=[{"code":"us-east-1","nodes":3,"namespace":"ns-east"},{"code":"eu-west-1","nodes":3,"namespace":"ns-west"}]' \ -n $NAMESPACE ``` If the annotation is missing, the controller defaults to the operator's configured cloud region. For single-region clusters this default is usually correct and the annotation can be omitted. The fallback order is: (1) `migration-regions` annotation, (2) `regionCode` and `cloudProvider` annotations, (3) operator environment configuration, (4) default `us-east1`. For single-region clusters, the default is usually acceptable. ## Step 3: Verify StatefulSet is stable All replicas must be ready before migration begins. Run the following `kubectl` commands to validate: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get sts $STS_NAME -n $NAMESPACE # READY column must equal DESIRED kubectl get pods -l app.kubernetes.io/name=cockroachdb -n $NAMESPACE # All pods must be Running/Ready ``` There must be no ongoing rolling updates, scale operations, or pending evictions on the cluster. ## Step 4: Install CockroachDB operator with migration enabled Run the following command to install the operator with migration enabled. This registers the migration controller which watches for the `crdb.io/migrate` label. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade --install crdb-operator cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 \ --set migration.enabled=true ``` * `migration.enabled=true` on the **operator chart** enables the migration controller and registers the conversion webhook. * Helm StatefulSet migrations do not have a pre-existing public operator, so the default `appLabel=cockroach-operator` works without modification. Verify the operator is running and CRDs are available: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get pods -l app=cockroachdb-operator -n $NAMESPACE kubectl get crd crdbclusters.crdb.cockroachlabs.com # Verify both API versions are accessible (conversion webhook is active) kubectl api-resources | grep crdbclusters ``` If a public operator is also running in the cluster for other namespaces, scope the CockroachDB operator to the target namespace and use a distinct `appLabel` to avoid selector conflicts. Without `watchNamespaces`, the CockroachDB operator's cluster controller will attempt to reconcile all `CrdbClusters` cluster-wide, interfering with clusters managed by the public operator. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade --install crdb-operator cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 \ --set migration.enabled=true \ --set appLabel=cockroachdb-operator \ --set watchNamespaces=$NAMESPACE ``` When migrating clusters across multiple namespaces, migrate one namespace at a time. Update `watchNamespaces` (or use a comma-separated list) to include additional namespaces only after the previous migration is complete. ## Step 5: Start migration Initiate the migration by labeling the StatefulSet: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label sts $STS_NAME crdb.io/migrate=start -n $NAMESPACE ``` The operator detects this label and begins the migration automatically. ## Step 6: Monitor migration The following sections describe how to monitor the ongoing migration. ### Phase-specific checks The following table describes the high-level events to monitor for progress during each migration phase: | Phase | What to watch | | - | - | | Init | `kubectl describe crdbcluster $STS_NAME` for MigrationStarted event | | CertMigration | For self-signer: `kubectl get secret $STS_NAME-node-secret -n $NAMESPACE`. For cert-manager: check the secret name from the Certificate CR (`kubectl get certificate $STS_NAME-node -n $NAMESPACE -o jsonpath='{.spec.secretName}'`). For user-provided certs: your existing secret is used directly. TLS clusters only | | PodMigration | `kubectl get crdbnode -n $NAMESPACE -w` for one node per pod | | Finalization | `kubectl get crdbcluster $STS_NAME -o jsonpath='{.status.migration.message}'` for "Finalization complete" | | Complete | After StatefulSet deletion; `spec.mode: MutableOnly` and `crdb.io/migrate` label changes to `complete` | ### DB Console The DB Console is accessible via the public service throughout migration. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Port-forward to access DB Console kubectl port-forward svc/${STS_NAME}-public 8080 -n $NAMESPACE # Then open https://localhost:8080 in your browser ``` Key things to monitor in the DB Console: * **Node List**: Watch for nodes joining and leaving as migration progresses. Total node count stays constant (new CrdbNode created before old STS pod is removed). * **Replication Status**: Under-replicated and unavailable ranges should stay at zero. The migration controller waits for under-replicated ranges to clear before proceeding to the next node. * **Ranges Dashboard**: Under-replicated ranges counter should not increase during migration. ### Prometheus metrics ``` crdb_operator_migration_phase{cluster, namespace, phase} crdb_operator_migration_pods_total{cluster, namespace} crdb_operator_migration_pods_migrated{cluster, namespace} crdb_operator_migration_duration_seconds{cluster, namespace, phase} crdb_operator_migration_errors_total{cluster, namespace, phase, error_type} crdb_operator_migration_rollbacks_total{cluster, namespace, reason} ``` ### CockroachDB health checks The controller performs these checks automatically between each node migration, but you can verify manually: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check under-replicated ranges (should be 0) # During migration, STS pods use container name "db"; after migration, CrdbNode pods use "cockroachdb" kubectl exec $STS_NAME-0 -n $NAMESPACE -c db -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT sum((metrics->>'ranges.underreplicated')::INT8) FROM crdb_internal.kv_store_status;" # Check all nodes are live (count should match total nodes) kubectl exec $STS_NAME-0 -n $NAMESPACE -c db -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT count(DISTINCT node_id) FROM crdb_internal.kv_store_status;" # For insecure clusters, replace --certs-dir with --insecure ``` ### Check migration phase ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.status.migration.phase} {.status.migration.message}' -w ``` ### Monitor Kubernetes events ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get events -n $NAMESPACE \ --field-selector involvedObject.name=$STS_NAME \ --sort-by='.lastTimestamp' ``` ### Watch `CrdbNode` creation during the PodMigration phase ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbnode -n $NAMESPACE \ -l crdb.cockroachlabs.com/cluster=$STS_NAME -w ``` ### Troubleshooting pauses during PodMigration During PodMigration, if a newly created CrdbNode does not pass health checks within **10 minutes**, the controller automatically pauses migration by setting the phase to `PhaseStopped`. Health checks run every **10 seconds** and verify: 1. CrdbNode has `PodReady=True` condition 2. Pod is in `Running` phase with `Ready=True` condition 3. SQL health check passes (zero under-replicated ranges and correct live node count) 4. Pod is registered in the headless service endpoints When auto-paused, investigate the stuck node and resume with `kubectl label sts $STS_NAME crdb.io/migrate=start --overwrite`. ### PDB behavior during migration * **Init through PodMigration**: The original Helm PDB remains active. Pod disruption protection is maintained throughout. * **Finalization**: The controller deletes the old PDB (`{name}` or `{name}-budget`) and immediately creates the new PDB (`{name}-pdb`). There is no gap in protection. * **Rollback**: All PDB variants are deleted (`{name}`, `{name}-budget`, `{name}-pdb`). The original PDB is not recreated by the migration controller. It is recreated by the Helm chart on the next `helm upgrade` or by the Helm release's existing resources. ## Step 7: Delete StatefulSet After the finalization phase is complete, the controller stops processing and waits for the user to manually delete the StatefulSet. The StatefulSet is intentionally left intact. Once deleted, the controller sets `spec.mode=MutableOnly` and records `Phase=Complete`. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Verify Finalization is done (Mode is still Disabled at this point) kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.status.migration.message}' # Expected: Finalization complete. Delete the StatefulSet to mark migration complete. # Delete the StatefulSet to trigger Phase=Complete kubectl delete sts $STS_NAME -n $NAMESPACE # Verify completion (may take a few seconds) # Mode switches to MutableOnly and label changes to "complete" after STS deletion. kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.spec.mode} {.status.migration.phase}' # Expected: MutableOnly Complete ``` All StatefulSet pods are already at `replicas=0` by the time Finalization runs (scaled down one by one during PodMigration). Deleting the StatefulSet object does not evict any running pods. ## Step 8: Verify cluster health post-migration Run the following `kubectl` commands to validate that the new cluster is online and healthy: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # All CrdbNodes should be healthy kubectl get crdbnode -n $NAMESPACE -l crdb.cockroachlabs.com/cluster=$STS_NAME # All pods running kubectl get pods -n $NAMESPACE -l crdb.cockroachlabs.com/cluster=$STS_NAME # Verify data integrity from any CrdbNode pod # Note: post-migration, the container name is "cockroachdb" (not "db" as in the original STS) kubectl exec $STS_NAME-0 -n $NAMESPACE -c cockroachdb -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT count(*) FROM [SHOW RANGES];" # Verify under-replicated ranges are zero kubectl exec $STS_NAME-0 -n $NAMESPACE -c cockroachdb -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT sum((metrics->>'ranges.underreplicated')::INT8) FROM crdb_internal.kv_store_status;" ``` ### Verify preserved configurations ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # WAL failover (if configured) kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.spec.template.spec.walFailoverSpec}' # Logs PVC (if configured) kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.spec.template.spec.logsStore}' # Log-config ConfigMap (converted from Helm Secret) kubectl get configmap ${STS_NAME}-log-config -n $NAMESPACE # TLS certificates (secret names depend on cert type) # Self-signer: {name}-node-secret, {name}-client-secret (regenerated by migration) kubectl get secret $STS_NAME-node-secret -n $NAMESPACE kubectl get secret $STS_NAME-client-secret -n $NAMESPACE # cert-manager: secrets are managed by cert-manager (names from Certificate CR) kubectl get certificate $STS_NAME-node -n $NAMESPACE -o jsonpath='{.spec.secretName}' # User-provided: your original secrets are used directly # CA ConfigMap (created for all TLS cert types) kubectl get configmap $STS_NAME-ca-crt -n $NAMESPACE # PCR (if configured) kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.spec.template.spec.virtualCluster}' ``` ## Step 9: Prepare values.yaml for CockroachDB Helm chart Before running `helm upgrade`, create a `values.yaml` that matches the migrated CrdbCluster spec. The CockroachDB Helm chart generates a `CrdbCluster` from these values, so they must align with what migration produced. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Inspect the migrated CrdbCluster spec to extract the values you need kubectl get crdbcluster $STS_NAME -n $NAMESPACE -o yaml ``` You can create the `values.yaml` file automatically with a migration helper, and/or build the file manually by mapping existing values. ### Option A: Generate values.yaml automatically Build and run the migration helper binary in the root of the [cockroachdb/helm-charts](https://github.com/cockroachdb/helm-charts/tree/master) repository: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} make bin/migration-helper ./bin/migration-helper export-values \ --crdb-cluster $STS_NAME \ --namespace $NAMESPACE \ --output-dir ./manifests ``` Review the generated file: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cat ./manifests/values.yaml ``` If the generated file contains `cockroachdb.crdbCluster.rbac.serviceAccount.name`, keep that value as is. It preserves the service account used by the migrated cluster. ### Option B: Build values.yaml manually Key values to set (map each to your migrated spec): | Helm value | Source from migrated CrdbCluster | | - | - | | `cockroachdb.crdbCluster.image.name` | `spec.template.spec.image` | | `cockroachdb.crdbCluster.regions` | `spec.regions` (code, nodes, namespace, cloudProvider) | | `cockroachdb.tls.enabled` | `spec.tlsEnabled` | | `cockroachdb.crdbCluster.rbac.serviceAccount.name` | `spec.template.spec.serviceAccountName` (leave empty to use default fullname) | | `cockroachdb.crdbCluster.resources` | `spec.template.spec.podTemplate.spec.containers[0].resources` | | `cockroachdb.crdbCluster.rollingRestartDelay` | `spec.rollingRestartDelay` | | `cockroachdb.crdbCluster.clusterSettings` | `spec.clusterSettings` | If the source Helm release used custom values (affinity, tolerations, nodeSelector, etc.), carry those forward into the new values.yaml as well. ### Field mapping reference | Source (StatefulSet) | Migrated v1beta1 cluster shape | Helm adoption value | | - | - | - | | StatefulSet name | `CrdbCluster.metadata.name` | `k8s.fullnameOverride` | | Container image | `spec.template.spec.image` | `cockroachdb.crdbCluster.image.name` | | Data PVC template | `spec.template.spec.dataStore` | `cockroachdb.crdbCluster.dataStore` | | `--wal-failover=path=...` | `spec.template.spec.walFailoverSpec` | `cockroachdb.crdbCluster.walFailoverSpec` | | Dedicated `logsdir` PVC | `spec.template.spec.logsStore` | `cockroachdb.crdbCluster.log.logsStore` | | Helm log Secret | Converted to ConfigMap; `spec.template.spec.loggingConfigMapName` | `cockroachdb.crdbCluster.loggingConfigMapName` | | Service account | `spec.template.spec.podTemplate.spec.serviceAccountName` | `cockroachdb.crdbCluster.rbac.serviceAccount.name` with `create=false` | | `--locality` tier keys | `spec.template.spec.localityLabels` | Exported into values; patch `localityMappings` for custom labels | | Ingress intent | Preserved as annotation on CrdbCluster | `cockroachdb.crdbCluster.service.ingress` | | PCR config | `spec.template.spec.virtualCluster` | `cockroachdb.crdbCluster.virtualCluster` | ## Step 10: Annotate resources for Helm adoption The migration controller creates resources but does not annotate them for Helm ownership. For `helm upgrade` to manage these resources, they must carry Helm ownership annotations: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Namespace-scoped resources for RESOURCE in \ "crdbcluster/${STS_NAME}" \ "serviceaccount/${STS_NAME}" \ "service/${STS_NAME}-public" \ "role/${STS_NAME}" \ "rolebinding/${STS_NAME}"; do kubectl annotate "${RESOURCE}" \ meta.helm.sh/release-name="${RELEASE_NAME}" \ meta.helm.sh/release-namespace="${NAMESPACE}" \ -n "${NAMESPACE}" --overwrite kubectl label "${RESOURCE}" \ app.kubernetes.io/managed-by=Helm \ -n "${NAMESPACE}" --overwrite done # Ingress resources (only if your cluster has Ingress resources) for RESOURCE in \ "ingress/ui-${RELEASE_NAME}" \ "ingress/sql-${RELEASE_NAME}"; do kubectl get "${RESOURCE}" -n "${NAMESPACE}" 2>/dev/null && \ kubectl annotate "${RESOURCE}" \ meta.helm.sh/release-name="${RELEASE_NAME}" \ meta.helm.sh/release-namespace="${NAMESPACE}" \ -n "${NAMESPACE}" --overwrite && \ kubectl label "${RESOURCE}" \ app.kubernetes.io/managed-by=Helm \ -n "${NAMESPACE}" --overwrite done ``` If skipped, `helm upgrade` will fail with "resource already exists" errors. > [!NOTE] > > Do not annotate the migration-created ClusterRole/ClusterRoleBinding for Helm adoption. The CockroachDB Helm chart creates its own cluster-scoped RBAC with different names (`{fullname}-{namespace}-node-reader`). The migration-created ones are stale and should be deleted in the next step. ## Step 11: Delete stale resources The migration controller creates some resources that do not match what the CockroachDB Helm chart produces. These can be deleted before or after running `helm upgrade`: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Migration-created ClusterRole and ClusterRoleBinding use "{namespace}-{name}" naming. # The CockroachDB Helm chart creates its own with "{fullname}-{namespace}-node-reader" naming. # Delete the migration versions so they don't accumulate as orphans. kubectl delete clusterrole ${NAMESPACE}-${STS_NAME} --ignore-not-found kubectl delete clusterrolebinding ${NAMESPACE}-${STS_NAME} --ignore-not-found # Old ClusterRole and ClusterRoleBinding from the source Helm release (bare cluster name) kubectl delete clusterrole ${STS_NAME} --ignore-not-found kubectl delete clusterrolebinding ${STS_NAME} --ignore-not-found # Old PDB from source Helm chart (operator creates its own "{name}-pdb" format) kubectl delete pdb ${STS_NAME} -n ${NAMESPACE} --ignore-not-found kubectl delete pdb ${STS_NAME}-budget -n ${NAMESPACE} --ignore-not-found ``` ## Step 12: Configure LocalityMappings The migration controller preserves the `--locality` flag tier keys (e.g. `region`, `zone`) as `localityLabels` on the `CrdbNodeSpec`. `localityLabels` is deprecated in favor of `localityMappings`, which maps K8s node labels to CockroachDB locality tiers. The default mapping covers standard K8s topology labels (`topology.kubernetes.io/region` → `region`, `topology.kubernetes.io/zone` → `zone`). If your cluster uses custom K8s node labels for locality, update `localityMappings` to match. Each entry maps a K8s node label key to a CockroachDB locality tier name. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl patch crdbcluster $STS_NAME -n $NAMESPACE --type merge -p ' spec: template: spec: localityMappings: - nodeLabel: "my-custom-label/region" localityLabel: "region" - nodeLabel: "my-custom-label/zone" localityLabel: "zone" ' ``` If you are using the standard `topology.kubernetes.io/*` labels, the kubebuilder defaults are correct and no action is needed. ## Step 13: Run Helm upgrade with CockroachDB chart Before upgrading, verify the operator has fully reconciled the migrated cluster. Do not proceed until `generation` and `observedGeneration` match and all pods are running. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.metadata.generation} {.status.observedGeneration}' # Both values should match kubectl get pods -n $NAMESPACE -l crdb.cockroachlabs.com/cluster=$STS_NAME # All pods should be Running and Ready ``` ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade ${RELEASE_NAME} cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} \ --namespace ${NAMESPACE} \ --values ./manifests/values.yaml ``` Verify the upgrade succeeded and no resources were duplicated: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # CrdbCluster should be managed by Helm now kubectl get crdbcluster $STS_NAME -n $NAMESPACE -o jsonpath='{.metadata.labels.app\.kubernetes\.io/managed-by}' # Expected: Helm # ClusterRole should use the new naming convention kubectl get clusterrole | grep $STS_NAME # Expected: {fullname}-{namespace}-node-reader (created by Helm chart) ``` After adoption is verified, consider performing a rolling restart to confirm chart-managed configuration is fully applied. Post-migration there is no StatefulSet, so trigger a rolling restart via `helm upgrade` with an updated timestamp: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade ${RELEASE_NAME} cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} \ --namespace ${NAMESPACE} \ --set cockroachdb.crdbCluster.timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ --values ./manifests/values.yaml ``` Verify generation matching to confirm the operator has reconciled: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.metadata.generation} {.status.observedGeneration}' # Both values should match ``` ### Update certificate mode after adoption After migration, all certificate references are stored as `externalCertificates` on the CrdbCluster spec, regardless of the original cert type. The `export-values` tool outputs these as `cockroachdb.tls.externalCertificates`. After Helm adoption, update your `values.yaml` to use the cert mode that matches your intended ongoing management: * **Self-signer**: Switch to `cockroachdb.tls.selfSigner.enabled: true` and remove the `externalCertificates` block. The operator's self-signer will manage cert rotation going forward. The migration-created `{name}-node-secret` and `{name}-client-secret` secrets become stale once the self-signer creates its own. Delete them after verifying the new certs are working. * **cert-manager**: Switch to `cockroachdb.tls.certManager.enabled: true` with the appropriate issuer reference. The migration preserved the Certificate CR and its `spec.secretName`, so cert-manager continues to manage rotation. Remove the `externalCertificates` block from values. * **User-provided / External**: Keep `cockroachdb.tls.externalCertificates` as exported. You are responsible for cert rotation. After updating cert mode, run `helm upgrade` again and verify pods are healthy. Clean up any stale secrets that are no longer referenced: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check which secrets are actually mounted by pods kubectl get pod $STS_NAME-0 -n $NAMESPACE -o jsonpath='{.spec.volumes[*].secret.secretName}' # Delete stale migration-created secrets if they are no longer mounted kubectl delete secret $STS_NAME-node-secret -n $NAMESPACE --ignore-not-found kubectl delete secret $STS_NAME-client-secret -n $NAMESPACE --ignore-not-found ``` ## Troubleshooting Follow these troubleshooting steps if there are issues with the migration: ### Migration stuck at PodMigration phase If a node fails health checks for more than 10 minutes, migration auto-pauses to `PhaseStopped`. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check why migration stopped kubectl get crdbcluster $STS_NAME -n $NAMESPACE \ -o jsonpath='{.status.migration.lastError}' # Check pod status kubectl describe pod $STS_NAME- -n $NAMESPACE # Check CrdbNode status kubectl get crdbnode $STS_NAME- -n $NAMESPACE -o yaml # Resume after fixing the issue kubectl label sts $STS_NAME crdb.io/migrate=start --overwrite -n $NAMESPACE ``` ### Insecure cluster migration The controller detects insecure clusters (`--insecure` flag) and skips certificate migration. An `InsecureClusterMigration` warning event is emitted. No action is needed unless you want to enable TLS post-migration. ### Under-replicated ranges If health checks report under-replicated ranges, wait for replication to catch up. The controller retries every 10 seconds. If ranges remain under-replicated for 10 minutes, migration pauses. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # StatefulSet pods use -c db. Migrated CrdbNode pods use -c cockroachdb. kubectl exec $STS_NAME-0 -n $NAMESPACE -c db -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT sum((metrics->>'ranges.underreplicated')::INT8) FROM crdb_internal.kv_store_status;" ``` ### Status conflict errors Status update conflicts are normal during migration (multiple controllers may update the same object). The controller retries immediately on conflict. If you see repeated conflict errors in logs, verify that no other controller is competing for the CrdbCluster status. ### Verifying RBAC ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check namespace-scoped RBAC kubectl get role $STS_NAME -n $NAMESPACE kubectl get rolebinding $STS_NAME -n $NAMESPACE # Check cluster-scoped RBAC (namespace-qualified names) kubectl get clusterrole ${NAMESPACE}-${STS_NAME} kubectl get clusterrolebinding ${NAMESPACE}-${STS_NAME} # Verify ServiceAccount kubectl get sa $STS_NAME -n $NAMESPACE ``` # Migrate from the Public Operator Source: https://docs.cockroachlabs.com/docs/stable/migrate-cockroachdb-kubernetes-operator This guide covers the automatic migration of a CockroachDB cluster managed via the Public operator to the CockroachDB Operator. The CockroachDB Operator's migration controller handles the complex logic of migrating nodes, certificates, and resources automatically, ensuring a seamless transition with minimal manual intervention. These instructions assume that you are migrating from a cluster that is managed with kubectl via the following yaml files: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/crds.yaml kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml kubectl apply -f https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/examples/example.yaml ``` > [!TIP] > > If your existing cluster was created as a StatefulSet using Helm, refer to the [Helm migration guide](/docs/v26.4/migrate-cockroachdb-kubernetes-helm). ## Compatibility Before starting migration, verify your cluster configuration is supported by the migration controller: | Feature | Supported | Notes | | - | - | - | | Self-signer certs (operator built-in) | Yes | Regenerated with join service DNS SANs; originals preserved | | cert-manager certs | Yes | Certificate CR updated with join service DNS SANs; issuer references preserved | | External certs (user-provided secrets) | Yes | Secret references preserved as ExternalCertificates | | Custom `NodeTLSSecret` / `ClientTLSSecret` | Yes | CrdbNode pods mount user's secrets directly; cert regeneration skipped (see prerequisites) | | Insecure clusters (TLS disabled) | Yes | Detected from `--insecure` flag; cert migration phase skipped entirely | | [WAL failover (dedicated PVC)](/docs/v26.4/wal-failover) | No | WAL failover detection only runs for Helm migrations. Not supported for operator path | | Dedicated logs PVC (`logsdir` / `logs-dir`) | No | LogsStore detection only runs for Helm migrations. Not supported for operator path | | PCR (virtualized/standby) | No | PCR detection only runs for Helm migrations (init job pattern). Not supported for operator path | | Custom service account | Yes | Preserved with `create: false` | | Custom start flags / `additionalArgs` | Partial | Known operator-managed flags excluded; `additionalArgs` converted to `startFlags.upsert` | | `cache` / `max-sql-memory` | Yes | Converted to start flags | | [Multi-region](/docs/v26.4/multiregion-overview) | Yes | Requires `regionCode` and `cloudProvider` annotations before starting | | Ingress | Partial | v1alpha1 ingress config preserved as annotation on v1beta1. Ingress resources not modified. Manual adoption required | | ServiceMonitor / PodMonitor | No | Not handled by migration. Must be recreated manually to match new pod labels | | NetworkPolicy | No | Must be recreated manually if present | | Log ConfigMap key format | Yes | `logging.yaml` key automatically renamed to `logs.yaml` (reversed on rollback) | | Using both operators | Partial | See [co-operating public and CockroachDB operators](#co-operating-public-and-cockroachdb-operators) for details. | ## Before you begin Verify the following before starting migration: * CockroachDB cluster is managed by the Public Operator (v1alpha1 CrdbCluster). * All StatefulSet pods are Running and Ready with no pending rolling updates or scale operations. * `kubectl` and `helm` are installed and configured with access to the target cluster. * For multi-region clusters: cloud region and provider labels are applied to K8s nodes. * You have the `regionCode` and `cloudProvider` values for your cluster. * You have reviewed the [Compatibility](#compatibility) table and confirmed your configuration is supported, or otherwise are prepared to manually recreate unsupported feature configurations. * The public operator is accessible and running (required for rollback capability). * **If you plan to create new v1beta1 clusters while the public operator is running**: Patch the public operator's webhooks to use `matchPolicy: Exact`. * **If using custom `NodeTLSSecret` / `ClientTLSSecret`**: Your certificates include join service DNS SANs (`{cluster-name}-join`, `{cluster-name}-join.{namespace}`, `{cluster-name}-join.{namespace}.svc.cluster.local`). The migration controller cannot regenerate certificates when custom secrets are provided (the CA private key is not available). ## Migration controller overview The following sections describe how the automated migration controller handles a migration from the Public operator to the CockroachDB operator: ### What the migration controller does automatically * Detects cert-manager, self-signer, or custom TLS secrets. Self-signer and cert-manager certs are regenerated with join service DNS SANs automatically. When custom `NodeTLSSecret` / `ClientTLSSecret` are set, skips cert regeneration and mounts the user's secrets directly. * Creates RBAC resources with namespace-qualified names for cluster-scoped resources. * Migrates ConfigMap key format (`logging.yaml` to `logs.yaml`). * Converts v1alpha1 CrdbCluster spec to v1beta1 via conversion webhook. * Deletes old PDB and creates a new one during finalization (no protection gap because the new PDB is created immediately after old PDB deletion). * Updates service selectors and restores them on rollback. * Migrates nodes one at a time, verifying cluster health between each node. * Preserves Ingress configuration from v1alpha1 CR as annotation on v1beta1 CrdbCluster. * Removes `crdb.io/skip-reconcile` label as the last step of rollback so the public operator resumes control cleanly. ### Controlling migration (Stop / Resume / Rollback) The following section describe how to safely manage an in-progress migration. #### Stop (Pause) Pauses migration at the current phase. No resources are deleted. CrdbNodes already created remain running and serving traffic. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=stop --overwrite -n $NAMESPACE ``` #### Resume There is no separate "resume" label value. Use `start` again to resume from the paused phase. The controller detects the `PhaseStopped` state internally and resumes at the correct phase based on how many nodes have already been migrated. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=start --overwrite -n $NAMESPACE ``` #### Stop during rollback If rollback is in progress and you apply the stop label, the controller pauses the rollback. The status message indicates that migration was stopped while in `RollbackInProgress`. To resume the rollback: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=rollback --overwrite -n $NAMESPACE ``` To resume forward migration instead: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=start --overwrite -n $NAMESPACE ``` `start` resumes forward migration, while `rollback` resumes rollback. #### Gap detection on stop If stop is requested between scaling down the StatefulSet and creating the replacement CrdbNode, the controller detects the gap and scales the StatefulSet back up before entering `PhaseStopped`. This keeps every ordinal represented by either a StatefulSet pod or a CrdbNode pod while migration is paused. #### Rollback Rollback is safe at any phase before Complete. Removing the label triggers automatic rollback. The controller automatically: 1. Deletes all CrdbNodes and waits for their pods to terminate. 2. Restores StatefulSet to original replica count. 3. Removes migration labels (`crdb.cockroachlabs.com/cluster`, `svc`) from pods. 4. Deletes CA ConfigMap (`{name}-ca-crt`) and migration-created cert secrets (`{name}-node-secret`, `{name}-client-secret`). 5. Reverses ConfigMap key migration (`logs.yaml` back to `logging.yaml`). 6. Deletes all PDB variants (`{name}`, `{name}-budget`, `{name}-pdb`). 7. Restores original service selectors (`app.kubernetes.io/component`, `app.kubernetes.io/instance`). 8. Deletes namespace-qualified ClusterRole and ClusterRoleBinding (`{namespace}-{name}`). 9. Sets CrdbCluster `Mode=Disabled`. 10. Removes `crdb.io/skip-reconcile` label last so the public operator resumes control. All cleanup steps are non-fatal. If a resource is already deleted or inaccessible, the controller logs a warning and continues with the remaining cleanup. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate- -n $NAMESPACE ``` **What happens to data during rollback?** Data written during migration is safe. CockroachDB replicates data across nodes. When CrdbNodes are deleted, their data is re-replicated to the remaining STS pods (which are scaled back up). No data is lost as long as the replication factor is maintained. **During rollback, two sets of pods may briefly coexist.** The controller scales the STS back up before deleting CrdbNodes, ensuring the cluster always has enough replicas. **What if the public operator was already uninstalled?** Rollback still works. It restores the StatefulSet and removes migration artifacts. However, without the public operator running, nothing will reconcile the StatefulSet after rollback. You would need to reinstall the public operator or manage the StatefulSet manually. **What happens to PVCs during rollback?** When CrdbNodes are deleted, their PVCs are also deleted. When the StatefulSet scales back up, Kubernetes creates new PVCs. Unlike forward migration (which reuses existing PVCs), rollback creates fresh storage. Data safety is maintained through CockroachDB's built-in replication. Data is re-replicated from the nodes that remain healthy throughout the process. > [!CAUTION] > > For operator migrations, the public operator must still be running (or at least its CRDs and webhook must be available) for rollback to fully succeed. The controller removes `skip-reconcile` as the last rollback step, allowing the public operator to resume reconciliation. If the public operator has been completely uninstalled (including CRDs), the StatefulSet is restored but nothing will reconcile it. You would need to reinstall the public operator or manage the cluster manually. #### Rollback validation After rollback, the controller enters a validation phase (`PhaseRollbackComplete`) and verifies the following: * All CrdbNodes are deleted. * StatefulSet is restored to original replica count. * All pods are ready. * Headless service has no v1beta1 ownerReferences. The controller only removes the `skip-reconcile` label and clears migration status after all checks are confirmed. #### Rollback safety by phase | Phase | Rollback safe? | Notes | | - | - | - | | Init | Yes | Only a CrdbCluster has been created; no pods affected | | CertMigration | Yes | Only cert secrets created; no pods affected | | PodMigration | Yes | Controller deletes CrdbNodes and scales STS back up | | Finalization | Conditional | Safe if STS still exists. If STS was already deleted, rollback sets `PhaseFailed` | | Complete | No | STS has been deleted. Manual recovery required | #### Label values reference | Label Value | Who Sets It | Meaning | | - | - | - | | `start` | User | Begin or resume migration | | `stop` | User | Pause migration | | `rollback` | User | Request rollback (same as removing label) | | `in-progress` | Controller | Migration is actively running | | `stopped` | Controller | Migration is paused | | `complete` | Controller | Migration finished successfully | | `failed` | Controller | Migration hit an unrecoverable error | | (removed) | User | Triggers rollback | #### Rollback after complete Once `Phase=Complete`, automated rollback is not possible. The StatefulSet has been deleted. Manual recovery steps: 1. Delete all CrdbNodes 2. Manually recreate the StatefulSet with original spec 3. Scale up and verify cluster health 4. Remove the migration label ### Certificate detection The controller automatically detects your certificate method. No manual configuration is needed. * **cert-manager**: If cert-manager Certificate CRs exist for the cluster (`{name}-node`), the controller updates the Certificate CR with join service DNS SANs and preserves the issuer references. cert-manager then regenerates the secrets automatically. CrdbNode pods mount from the cert-manager-managed secret (the name from `spec.secretName` in the Certificate CR), not `{name}-node-secret`. This keeps cert-manager's automatic rotation working after migration. * **Self-signer** (operator built-in): The controller loads the existing CA from cluster secrets, regenerates node and client certificates with join service DNS SANs, and writes them to the destination secrets (`{name}-node-secret`, `{name}-client-secret`). CrdbNode pods mount from `{name}-node-secret`. The regenerated certificates have a 1-year TTL and are stored as `ExternalCertificates` in the v1beta1 spec. The operator does not auto-rotate `ExternalCertificates`, so after migration you should switch to `cockroachdb.tls.selfSigner.enabled: true` via Helm adoption to enable automatic rotation. If you delay this step, the certs will expire silently after one year. * **External certs**: If neither cert-manager CRs nor self-signer secrets are found, the controller preserves existing secret references as ExternalCertificates in the v1beta1 spec. * **Custom secret names**: If the v1alpha1 spec has `NodeTLSSecret` or `ClientTLSSecret` set, the controller skips cert regeneration entirely because the CA private key is not available. CrdbNode pods mount the user's existing secrets directly. The user must update their certificates to include join service DNS SANs **before** starting the migration (see prerequisites). * **Insecure clusters**: Detected from the `--insecure` start flag. The entire cert migration phase is skipped. An `InsecureClusterMigration` warning event is emitted. > [!NOTE] > > Regardless of the original cert type, after migration all certificate secret names are stored as `ExternalCertificates` on the CrdbNode spec. This is the internal representation used by the operator to mount the correct secrets into pods. ## Co-operating public and CockroachDB operators The CockroachDB operator and the public operator can run side by side during migration. Installing the CockroachDB operator with `migration.enabled=true` replaces the CRD with a dual-version CRD (v1alpha1 + v1beta1) and registers a conversion webhook. Existing clusters continue to work normally. ### Supported scenarios | Scenario | Behavior | | - | - | | Existing v1alpha1 clusters (not being migrated) | Continue to be reconciled by the public operator. The CockroachDB Operator ignores them (`Mode=Disabled`). | | New v1alpha1 clusters created with both operators present | Reconciled by the public operator. The CockroachDB Operator's v1beta1 webhooks do not intercept v1alpha1 requests. | | New v1beta1 clusters created with both operators present | The CockroachDB Operator's mutating webhook automatically injects `crdb.io/skip-reconcile=true`. The public operator sees this label and skips reconciliation. | | Updating existing v1alpha1 clusters | Works normally. Only the public operator's webhooks validate the request. | ### Unsupported scenarios | Scenario | Reason | | - | - | | Creating v1beta1 clusters without patching public operator webhooks | The public operator's webhooks use `matchPolicy: Equivalent` (the Kubernetes default), so they intercept v1beta1 requests after converting them to v1alpha1. The converted object fails the public operator's validation. | | Both operators reconciling the same cluster | Only one operator should own a cluster at a time. Use `crdb.io/skip-reconcile=true` to hand off. | | Running both operators with overlapping namespace scopes | Untested. Use `watchNamespaces` to separate them if needed. | ### How webhook isolation works Both operators' webhooks must use `matchPolicy: Exact` to prevent cross-version interception. The CockroachDB operator's webhooks ship with this setting. The public operator's webhooks use the Kubernetes default (`Equivalent`), which causes them to intercept v1beta1 requests after Kubernetes converts them to v1alpha1. To create v1beta1 clusters while the public operator is present, update the public operator's webhooks to use `matchPolicy: Exact`. **Option 1: Edit the public operator manifest before installing.** Download the manifest, add `matchPolicy: Exact` to both webhook entries, then apply: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -sL https://raw.githubusercontent.com/cockroachdb/cockroach-operator/v2.18.3/install/operator.yaml \ | sed '/rules:/i\ matchPolicy: Exact' \ | kubectl apply -f - ``` **Option 2: Patch the live webhook configs.** This does not persist across public operator redeploys: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl patch validatingwebhookconfiguration cockroach-operator-validating-webhook-configuration \ --type=json -p='[{"op":"add","path":"/webhooks/0/matchPolicy","value":"Exact"}]' kubectl patch mutatingwebhookconfiguration cockroach-operator-mutating-webhook-configuration \ --type=json -p='[{"op":"add","path":"/webhooks/0/matchPolicy","value":"Exact"}]' ``` With both sides using `matchPolicy: Exact`, a v1alpha1 request triggers only the public operator's webhooks, and a v1beta1 request triggers only the CockroachDB operator's webhooks. This patching is only needed if you plan to create new v1beta1 clusters while the public operator is still running. Migration of existing v1alpha1 clusters does not require patching because the migration controller works with the v1alpha1 API directly. ### How conversion works **v1alpha1 clusters without `skip-reconcile`** are converted to v1beta1 with `Mode=Disabled` for storage. The CockroachDB operator ignores clusters in this mode. **v1beta1 cluster protection**: The CockroachDB operator's mutating webhook injects `crdb.io/skip-reconcile=true` on every v1beta1 CrdbCluster. This label is stored on the object and carried through to the v1alpha1 view via ObjectMeta, so the public operator sees it and skips reconciliation. In summary, you can: * Keep existing v1alpha1 clusters running with the public operator * Create new v1alpha1 clusters while the CockroachDB Operator is installed * Create new v1beta1 clusters while the public operator is still running * Migrate clusters one by one at your own pace ## Multi-cluster migration strategy When you have multiple clusters across different namespaces, you can migrate them one at a time while the public operator continues managing the remaining v1alpha1 clusters. ### Deployment pattern Deploy one namespace-scoped CockroachDB Operator per namespace using `watchNamespaces`. This provides clean isolation where each operator manages only the clusters in its namespace. A single operator watching multiple namespaces can also work, but has less isolation. ``` ns-prod-1: public operator cluster-1 + CockroachDB Operator (scoped, migration=true) ns-prod-2: public operator cluster-2 (no CockroachDB Operator yet) ns-staging: CockroachDB Operator (scoped, migration=false) + fresh v1beta1 cluster ``` ### The migration flag rule At least one CockroachDB operator must have `migration.enabled=true` as long as any v1alpha1 cluster exists anywhere in the Kubernetes cluster. The CRD conversion webhook is a cluster-wide resource. The public operator reads and writes v1alpha1 CrdbClusters, and since the storage version is v1beta1, every v1alpha1 interaction goes through the webhook. Only operators started with `migration.enabled=true` register the `/convert` endpoint. It does not matter which operator has the flag. The conversion endpoint is stateless and handles requests for any namespace. But at least one must be running and reachable. Operators that only manage fresh v1beta1 clusters do not need the migration flag. When an operator starts without migration enabled, it checks the CRD's `storedVersions` field. If v1alpha1 is present and an existing conversion webhook is already configured (by another operator), it preserves the webhook and starts normally. ### Creating new v1beta1 clusters during migration You can create new v1beta1 clusters at any point during migration. Install a namespace-scoped CockroachDB operator in a separate namespace and create v1beta1 CrdbCluster resources directly. The mutating webhook automatically injects `crdb.io/skip-reconcile=true` so the public operator ignores these clusters. The new operator does not need `migration.enabled=true` as long as another operator already has it enabled. ### Migrated clusters and the public operator After a cluster is migrated, the public operator can remain running while it manages other v1alpha1 clusters. Migrated clusters can be updated by the CockroachDB Operator or CockroachDB Helm chart independently of the public operator. Keep `crdb.io/skip-reconcile=true` on migrated clusters while the public operator is still running. Removing it allows the public operator to reconcile the migrated cluster and can recreate StatefulSet resources that conflict with CrdbNodes. ### Gradual migration across namespaces **Phase 1 - Migrate the first namespace:** 1. Install a CockroachDB Operator in ns-1 with `migration.enabled=true`, `appLabel=cockroachdb-operator`, and `watchNamespaces=ns-1`. 2. Apply `skip-reconcile` and cloud annotations on the cluster in ns-1. 3. Label the cluster with `crdb.io/migrate=start`. 4. Monitor migration, delete StatefulSet when in Finalization. 5. The cluster in ns-2 continues running under the public operator, unaffected. **Phase 2 - Deploy fresh v1beta1 clusters in other namespaces (optional):** 1. Install a CockroachDB Operator in ns-3 with `migration.enabled=false`, `appLabel=cockroachdb-operator`, and `watchNamespaces=ns-3`. This works because the ns-1 operator already has the conversion webhook configured. 2. Create v1beta1 clusters directly using the CockroachDB Helm chart. **Phase 3 - Migrate the remaining namespace:** 1. Either expand ns-1's `watchNamespaces` to include ns-2, or install a new CockroachDB operator in ns-2 with `migration.enabled=true`, `appLabel=cockroachdb-operator`. 2. Apply `skip-reconcile` and cloud annotations on the cluster in ns-2. 3. Migrate the cluster. **Phase 4 - Finalize (all v1alpha1 clusters are migrated):** 1. Remove the public operator (no v1alpha1 clusters remain). 2. Patch `storedVersions` to remove v1alpha1 (see Step 13). 3. The migration flag can optionally be removed (see Step 14). ### What happens if things go wrong | Scenario | What happens | What to do | | - | - | - | | The only migration-enabled operator goes down | v1alpha1 reads/writes fail (webhook unreachable). v1beta1 clusters are unaffected. | Restart the operator or enable migration on another operator. | | Migration flag removed before `storedVersions` is patched | Operator preserves the existing webhook but does not register `/convert`. v1alpha1 interactions through the stale webhook return 404. v1beta1 clusters work fine. | Re-enable migration, or patch `storedVersions` if all clusters are migrated. | | `storedVersions` patched while v1alpha1 clusters still exist | The API server may not serve those objects correctly. | Do not patch `storedVersions` until all v1alpha1 clusters are migrated. If this happens, restore by adding v1alpha1 back to `storedVersions`. | | Public operator removed while v1alpha1 clusters remain | Those clusters become unmanaged. | Reinstall the public operator or migrate them first. | | `skip-reconcile` removed on a migrated cluster while public operator runs | Public operator recreates StatefulSet, conflicting with CrdbNodes. | Re-apply `skip-reconcile` immediately. Delete the recreated StatefulSet. | ## Step 1: Export environment variables Export the following environment variables based on your existing deployment: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # CRDBCLUSTER is the name of your v1alpha1 CrdbCluster CR. export CRDBCLUSTER=cockroachdb # NAMESPACE is the namespace where the CrdbCluster is installed. export NAMESPACE=default # CLOUD_PROVIDER is the cloud vendor where the K8s cluster is running. # Supported: gcp, aws, azure export CLOUD_PROVIDER=gcp # REGION corresponds to the cloud provider's identifier for this region. # It must match the "topology.kubernetes.io/region" label on K8s nodes. export REGION=us-central1 ``` ## Step 2: Apply cloud region and provider labels (multi-region only) CockroachDB uses K8s node labels for locality-based pod placement. These labels must exist before the operator starts scheduling pods. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # GCP kubectl label node \ topology.kubernetes.io/region=us-central1 \ topology.kubernetes.io/zone=us-central1-a \ cockroach.io/cloud=gcp # AWS kubectl label node \ topology.kubernetes.io/region=us-east-1 \ topology.kubernetes.io/zone=us-east-1a \ cockroach.io/cloud=aws # Azure kubectl label node \ topology.kubernetes.io/region=eastus \ topology.kubernetes.io/zone=eastus-1 \ cockroach.io/cloud=azure ``` ## Step 3: Pause the public operator The public operator must stop reconciling the cluster before installing the CockroachDB Operator. Without this, both controllers will fight over RBAC, PDB, and service selectors. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/skip-reconcile="true" -n $NAMESPACE ``` Wait until the public operator finishes any in-progress reconciliation before proceeding. Verify the StatefulSet is not currently rolling: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl rollout status sts $CRDBCLUSTER -n $NAMESPACE # Expected: statefulset rolling update complete # No new events should appear after applying the label kubectl describe crdbcluster $CRDBCLUSTER -n $NAMESPACE | grep -A5 Events ``` If the `skip-reconcile` label is not applied, migration will fail with: `missing required label: crdb.io/skip-reconcile=true` > [!CAUTION] > > The `crdb.io/skip-reconcile=true` label must remain on the v1alpha1 CrdbCluster for as long as the public operator is running. The public operator reconciles any CrdbCluster without this label and will recreate the StatefulSet and associated resources if it regains control. Do not remove this label until after the public operator has been fully uninstalled. Removing it while the public operator is still running will cause it to recreate the StatefulSet, potentially conflicting with the migrated CrdbNodes. ## Step 4: Annotate CrdbCluster with region and cloud provider Annotate the CR with region and cloud provider so they are preserved during the v1alpha1 to v1beta1 conversion: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl annotate crdbcluster $CRDBCLUSTER \ crdb.cockroachlabs.com/cloudProvider=$CLOUD_PROVIDER \ crdb.cockroachlabs.com/regionCode=$REGION \ --overwrite -n $NAMESPACE ``` The fallback order for region resolution is as follows: 1. `regions` annotation (for multi-region). 2. `regionCode` and `cloudProvider` annotations. 3. Operator environment configuration. 4. Default `us-east1`. For single-region clusters, the default may be acceptable. ## Step 5: Install CockroachDB operator with migration enabled Install the operator with migration enabled. The migration controller only acts on resources that have the `crdb.io/migrate` label, and the cluster controller skips clusters with `Mode=Disabled` (which the conversion webhook sets for all v1alpha1 clusters). The CockroachDB operator will not interfere with clusters that have not been explicitly marked for migration. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade --install crdb-operator cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 \ --set migration.enabled=true \ --set appLabel=cockroachdb-operator ``` > [!NOTE] > > The CockroachDB operator and the public operator can run side-by-side during migration. See [co-operating public and CockroachDB operators](#co-operating-public-and-cockroachdb-operators) for details. Setting `watchNamespaces` is optional. This setting restricts the CockroachDB operator to a subset of namespaces, which can be useful for reducing blast radius in large environments. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade --install crdb-operator cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 \ --set migration.enabled=true \ --set appLabel=cockroachdb-operator \ --set watchNamespaces=$NAMESPACE ``` `migration.enabled=true` on the **operator chart** enables the migration controller and registers the conversion webhook (translates between v1alpha1 and v1beta1). Verify the operator is running and the conversion webhook is active: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get pods -l app=cockroachdb-operator -n $NAMESPACE kubectl get crd crdbclusters.crdb.cockroachlabs.com # Verify both API versions are accessible (conversion webhook is active) kubectl get crdbclusters.v1alpha1.crdb.cockroachlabs.com $CRDBCLUSTER -n $NAMESPACE kubectl get crdbclusters.v1beta1.crdb.cockroachlabs.com $CRDBCLUSTER -n $NAMESPACE ``` Both commands should return the same CrdbCluster resource, confirming the conversion webhook is translating between API versions. The operator's ClusterRole and ClusterRoleBinding must use unique names to avoid overwriting the public operator's RBAC. The Helm chart handles this automatically. This migration flow sets `appLabel=cockroachdb-operator` so the CockroachDB operator's Deployment selector and Service selector do not collide with the public operator's `app=cockroach-operator` labels when both operators run in the same namespace. The operator chart default remains `appLabel=cockroach-operator` for normal upgrades and preview users to avoid changing the existing immutable Deployment selector. Use the distinct `appLabel` only for new migration/coexistence installs. When migrating clusters across multiple namespaces, migrate one namespace at a time. Update `watchNamespaces` (or use a comma-separated list) to include additional namespaces only after the previous migration is complete. ## Step 6: Start migration Initiate the migration by labeling the v1alpha1 CrdbCluster. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=start -n $NAMESPACE ``` ## Step 7: Monitor migration The following sections describe how to monitor the ongoing migration. ### Phase-specific checks The following table describes the high-level events to monitor for progress during each migration phase: | Phase | What to watch | | - | - | | Init | `kubectl describe crdbcluster $CRDBCLUSTER` for MigrationStarted event | | CertMigration | For self-signer: `kubectl get secret $CRDBCLUSTER-node-secret -n $NAMESPACE`. For cert-manager: check the secret name from the Certificate CR (`kubectl get certificate $CRDBCLUSTER-node -n $NAMESPACE -o jsonpath='{.spec.secretName}'`). For custom `NodeTLSSecret`: your existing secret is used directly. TLS clusters only | | PodMigration | `kubectl get crdbnode -n $NAMESPACE -w` for one node per pod | | Finalization | `kubectl get crdbcluster $CRDBCLUSTER -o jsonpath='{.status.migration.message}'` for "Finalization complete" | | Complete | After StatefulSet deletion; `spec.mode: MutableOnly` and `crdb.io/migrate` label changes to `complete` | ### DB Console The DB Console is accessible via the public service throughout migration. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Port-forward to access DB Console kubectl port-forward svc/${CRDBCLUSTER}-public 8080 -n $NAMESPACE # Then open https://localhost:8080 in your browser ``` Key things to monitor in the DB Console: * **Node List**: Watch for nodes joining and leaving as migration progresses. Total node count stays constant (new CrdbNode created before old STS pod is removed). * **Replication Status**: Under-replicated and unavailable ranges should stay at zero. The migration controller waits for under-replicated ranges to clear before proceeding to the next node. * **Ranges Dashboard**: Under-replicated ranges counter should not increase during migration. ### Prometheus metrics ``` crdb_operator_migration_phase{cluster, namespace, phase} crdb_operator_migration_pods_total{cluster, namespace} crdb_operator_migration_pods_migrated{cluster, namespace} crdb_operator_migration_duration_seconds{cluster, namespace, phase} crdb_operator_migration_errors_total{cluster, namespace, phase, error_type} crdb_operator_migration_rollbacks_total{cluster, namespace, reason} ``` ### CockroachDB health checks The controller performs these checks automatically between each node migration, but you can verify manually: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check under-replicated ranges (should be 0) # During migration, STS pods use container name "db"; after migration, CrdbNode pods use "cockroachdb" kubectl exec $CRDBCLUSTER-0 -n $NAMESPACE -c db -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT sum((metrics->>'ranges.underreplicated')::INT8) FROM crdb_internal.kv_store_status;" # Check all nodes are live (count should match total nodes) kubectl exec $CRDBCLUSTER-0 -n $NAMESPACE -c db -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT count(DISTINCT node_id) FROM crdb_internal.kv_store_status;" # For insecure clusters, replace --certs-dir with --insecure ``` ### Check migration phase The migration status is recorded on the v1beta1 CrdbCluster (created via conversion webhook). ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.status.migration.phase} {.status.migration.message}' -w ``` ### Monitor Kubernetes events ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get events -n $NAMESPACE \ --field-selector involvedObject.name=$CRDBCLUSTER \ --sort-by='.lastTimestamp' ``` ### Watch `CrdbNode` creation during the PodMigration phase ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbnode -n $NAMESPACE \ -l crdb.cockroachlabs.com/cluster=$CRDBCLUSTER -w ``` ### Troubleshooting pauses during PodMigration During PodMigration, if a newly created CrdbNode does not pass health checks within **10 minutes**, the controller automatically pauses migration by setting the phase to `PhaseStopped`. Health checks run every **10 seconds** and verify: 1. CrdbNode has `PodReady=True` condition 2. Pod is in `Running` phase with `Ready=True` condition 3. SQL health check passes (zero under-replicated ranges and correct live node count) 4. Pod is registered in the headless service endpoints When auto-paused, investigate the stuck node and resume with `kubectl label sts $CRDBCLUSTER crdb.io/migrate=start --overwrite`. ### PDB behavior during migration * **Init through PodMigration**: The original public operator PDB remains active. Pod disruption protection is maintained throughout. * **Finalization**: The controller deletes the old PDB (`{name}` or `{name}-budget`) and immediately creates the new PDB (`{name}-pdb`). There is no gap in protection. * **Rollback**: All PDB variants are deleted (`{name}`, `{name}-budget`, `{name}-pdb`). The original PDB is recreated by the public operator once `skip-reconcile` is removed. ## Step 8: Delete StatefulSet After the finalization phase is complete, the controller stops processing and waits for the user to manually delete the StatefulSet. The StatefulSet is intentionally left intact. Once deleted, the controller sets `spec.mode=MutableOnly` and records `Phase=Complete`. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Verify Finalization is done (Mode is still Disabled at this point) kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.status.migration.message}' # Expected: Finalization complete. Delete the StatefulSet to mark migration complete. # Delete the StatefulSet to trigger Phase=Complete kubectl delete sts $CRDBCLUSTER -n $NAMESPACE # Verify completion (may take a few seconds) # Mode switches to MutableOnly and label changes to "complete" after STS deletion. kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.spec.mode} {.status.migration.phase}' # Expected: MutableOnly Complete ``` All StatefulSet pods are already at `replicas=0` by the time Finalization runs (scaled down one by one during PodMigration). Deleting the StatefulSet object does not evict any running pods. ## Step 9: Verify cluster health post-migration Run the following `kubectl` commands to validate that the new cluster is online and healthy: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # All CrdbNodes should be healthy kubectl get crdbnode -n $NAMESPACE -l crdb.cockroachlabs.com/cluster=$CRDBCLUSTER # All pods running kubectl get pods -n $NAMESPACE -l crdb.cockroachlabs.com/cluster=$CRDBCLUSTER # Verify data integrity from any CrdbNode pod # Note: post-migration, the container name is "cockroachdb" (not "db" as in the original STS) kubectl exec $CRDBCLUSTER-0 -n $NAMESPACE -c cockroachdb -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT count(*) FROM [SHOW RANGES];" # Verify under-replicated ranges are zero kubectl exec $CRDBCLUSTER-0 -n $NAMESPACE -c cockroachdb -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT sum((metrics->>'ranges.underreplicated')::INT8) FROM crdb_internal.kv_store_status;" ``` ### Verify preserved configurations ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # ConfigMap key format (should be logs.yaml, not logging.yaml) kubectl get configmap -n $NAMESPACE -o yaml | grep -E "logging.yaml|logs.yaml" # TLS certificates (secret names depend on cert type) # Self-signer: {name}-node-secret, {name}-client-secret (regenerated by migration) kubectl get secret $CRDBCLUSTER-node-secret -n $NAMESPACE kubectl get secret $CRDBCLUSTER-client-secret -n $NAMESPACE # cert-manager: secrets are managed by cert-manager (names from Certificate CR) kubectl get certificate $CRDBCLUSTER-node -n $NAMESPACE -o jsonpath='{.spec.secretName}' # Custom NodeTLSSecret/ClientTLSSecret: your original secrets are used directly # CA ConfigMap (created for all TLS cert types) kubectl get configmap $CRDBCLUSTER-ca-crt -n $NAMESPACE ``` ### Verify v1alpha1 → v1beta1 field conversion Key fields converted during migration: | v1alpha1 field | v1beta1 field | | - | - | | `spec.image.name` | `spec.template.spec.image` | | `spec.grpcPort` / `spec.sqlPort` / `spec.httpPort` | `spec.template.spec.grpcPort` / `sqlPort` / `httpPort` | | `spec.cache` | `spec.template.spec.startFlags.upsert` (`--cache=`) | | `spec.maxSQLMemory` | `spec.template.spec.startFlags.upsert` (`--max-sql-memory=`) | | `spec.additionalArgs` | `spec.template.spec.startFlags.upsert` | | `spec.nodeTLSSecret` | CrdbNode mounts this secret directly (cert regeneration skipped) | | `spec.clientTLSSecret` | CrdbNode mounts this secret directly (cert regeneration skipped) | | `spec.logConfigMap` | `spec.template.spec.loggingConfigMapName` (key renamed `logging.yaml` → `logs.yaml`) | | `spec.terminationGracePeriodSecs` | Used directly in pod spec | | `spec.resources` | `spec.template.spec.podTemplate.spec.containers[0].resources` | ## Step 10: Configure LocalityMappings The migration controller preserves the `--locality` flag tier keys (e.g. `region`, `zone`) as `localityLabels` on the CrdbNodeSpec. `localityLabels` is deprecated in favor of `localityMappings`, which maps K8s node labels to CockroachDB locality tiers. The default mapping covers standard K8s topology labels (`topology.kubernetes.io/region` → `region`, `topology.kubernetes.io/zone` → `zone`). If your cluster uses custom K8s node labels for locality, update `localityMappings` to match. Each entry maps a K8s node label key to a CockroachDB locality tier name. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl patch crdbcluster $CRDBCLUSTER -n $NAMESPACE --type merge -p ' spec: template: spec: localityMappings: - nodeLabel: "my-custom-label/region" localityLabel: "region" - nodeLabel: "my-custom-label/zone" localityLabel: "zone" ' ``` If you are using the standard `topology.kubernetes.io/*` labels, the kubebuilder defaults are correct and no action is needed. ## Step 11: Cleanup public operator resources After verifying the migrated cluster is healthy, clean up old public operator resources. ### Migration-created RBAC (stale) ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Migration-created ClusterRole/ClusterRoleBinding use "{namespace}-{name}" naming kubectl delete clusterrole ${NAMESPACE}-${CRDBCLUSTER} --ignore-not-found kubectl delete clusterrolebinding ${NAMESPACE}-${CRDBCLUSTER} --ignore-not-found ``` ### Public operator RBAC ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Public operator's ClusterRole and ClusterRoleBinding kubectl delete clusterrole cockroachdb-operator --ignore-not-found kubectl delete clusterrolebinding cockroachdb-operator --ignore-not-found ``` ### Public operator deployment Only do this after all clusters managed by the public operator have been migrated. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Delete the public operator Deployment kubectl delete deployment cockroach-operator-manager -n cockroach-operator-system --ignore-not-found ``` > [!CAUTION] > > Do not delete `crdbclusters.crdb.cockroachlabs.com`, `crdbnodes.crdb.cockroachlabs.com`, or `crdbtenants.crdb.cockroachlabs.com`. Those CRDs are shared by the migrated CockroachDB Operator resources. A later step removes `v1alpha1` from `storedVersions` after every v1alpha1 cluster has been migrated. ### Public operator webhook configurations ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # The public operator registers its own validation/mutation webhooks kubectl delete validatingwebhookconfiguration cockroach-operator-validating-webhook-configuration --ignore-not-found kubectl delete mutatingwebhookconfiguration cockroach-operator-mutating-webhook-configuration --ignore-not-found ``` ### Public operator ServiceAccount and RBAC in its namespace ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl delete serviceaccount cockroach-operator-sa -n cockroach-operator-system --ignore-not-found kubectl delete role cockroach-operator-role -n cockroach-operator-system --ignore-not-found kubectl delete rolebinding cockroach-operator-rolebinding -n cockroach-operator-system --ignore-not-found ``` ## Step 12: Adopt into CockroachDB Helm chart (Optional) Before adopting, verify the operator has fully reconciled the migrated cluster. Do not proceed until `generation` and `observedGeneration` match and all pods are running. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.metadata.generation} {.status.observedGeneration}' # Both values should match kubectl get pods -n $NAMESPACE -l crdb.cockroachlabs.com/cluster=$CRDBCLUSTER # All pods should be Running and Ready ``` If you want `helm upgrade` to manage the migrated CrdbCluster going forward, you need to annotate existing resources for Helm ownership and provide a `values.yaml` that matches the migrated spec. ### Prepare values.yaml Inspect the migrated CrdbCluster and map its spec to Helm values. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE -o yaml ``` You can create the `values.yaml` file automatically with a migration helper, and/or build the file manually by mapping existing values. ### Option A: Generate values.yaml automatically Build and run the migration helper binary in the root of the [cockroachdb/helm-charts](https://github.com/cockroachdb/helm-charts/tree/master) repository: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} make bin/migration-helper ./bin/migration-helper export-values \ --crdb-cluster $CRDBCLUSTER \ --namespace $NAMESPACE \ --output-dir ./manifests ``` Review the generated file: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cat ./manifests/values.yaml ``` If the generated file contains `cockroachdb.crdbCluster.rbac.serviceAccount.name`, keep that value as-is. This field preserves the service account used by the migrated cluster. ### Option B: Build values.yaml manually Key values to set: | Helm value | Source from migrated CrdbCluster | | - | - | | `cockroachdb.crdbCluster.image.name` | `spec.template.spec.image` | | `cockroachdb.crdbCluster.regions` | `spec.regions` (code, nodes, namespace, cloudProvider) | | `cockroachdb.tls.enabled` | `spec.tlsEnabled` | | `cockroachdb.crdbCluster.rbac.serviceAccount.name` | `spec.template.spec.serviceAccountName` (leave empty to use default fullname) | | `cockroachdb.crdbCluster.resources` | `spec.template.spec.podTemplate.spec.containers[0].resources` | | `cockroachdb.crdbCluster.rollingRestartDelay` | `spec.rollingRestartDelay` | | `cockroachdb.crdbCluster.clusterSettings` | `spec.clusterSettings` | The v1alpha1 CrdbCluster fields (cache, max-sql-memory, additionalArgs) were converted to `spec.template.spec.startFlags.upsert` during migration. Map these to the appropriate Helm values or pass them via `cockroachdb.crdbCluster.startFlags`. ### Field mapping reference | Source (v1alpha1) | Migrated v1beta1 shape | Helm adoption value | | - | - | - | | `metadata.name` | `CrdbCluster.metadata.name` | `k8s.fullnameOverride` | | `spec.image.name` | `spec.template.spec.image` | `cockroachdb.crdbCluster.image.name` | | `spec.dataStore` | `spec.template.spec.dataStore` | `cockroachdb.crdbCluster.dataStore` | | `spec.logConfigMap` | `spec.template.spec.loggingConfigMapName` (key renamed `logging.yaml` → `logs.yaml`) | `cockroachdb.crdbCluster.loggingConfigMapName` | | `spec.resources` | `spec.template.spec.podTemplate.spec.containers[0].resources` | `cockroachdb.crdbCluster.podTemplate.spec` | | `spec.cache` | `spec.template.spec.startFlags.upsert` (`--cache=`) | `cockroachdb.crdbCluster.startFlags` | | `spec.maxSQLMemory` | `spec.template.spec.startFlags.upsert` (`--max-sql-memory=`) | `cockroachdb.crdbCluster.startFlags` | | `spec.additionalArgs` | `spec.template.spec.startFlags.upsert` | `cockroachdb.crdbCluster.startFlags` | | Service account | `spec.template.spec.podTemplate.spec.serviceAccountName` | `cockroachdb.crdbCluster.rbac.serviceAccount.name` with `create=false` | | Pod annotations | `spec.template.spec.podTemplate.metadata.annotations` | `cockroachdb.crdbCluster.podTemplate.metadata.annotations` | | Priority class | `spec.template.spec.podTemplate.spec.priorityClassName` | `cockroachdb.crdbCluster.podTemplate.spec.priorityClassName` | | Ingress intent | Preserved as annotation on CrdbCluster | `cockroachdb.crdbCluster.service.ingress` | ### Annotate resources for Helm ownership ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export RELEASE_NAME="" # Namespace-scoped resources for RESOURCE in \ "crdbcluster/${CRDBCLUSTER}" \ "serviceaccount/${CRDBCLUSTER}-sa" \ "service/${CRDBCLUSTER}-public" \ "role/${CRDBCLUSTER}" \ "rolebinding/${CRDBCLUSTER}"; do kubectl annotate "${RESOURCE}" \ meta.helm.sh/release-name="${RELEASE_NAME}" \ meta.helm.sh/release-namespace="${NAMESPACE}" \ -n "${NAMESPACE}" --overwrite kubectl label "${RESOURCE}" \ app.kubernetes.io/managed-by=Helm \ -n "${NAMESPACE}" --overwrite done # Ingress resources (only if your cluster has Ingress resources) for RESOURCE in \ "ingress/ui-${CRDBCLUSTER}" \ "ingress/sql-${CRDBCLUSTER}"; do kubectl get "${RESOURCE}" -n "${NAMESPACE}" 2>/dev/null && \ kubectl annotate "${RESOURCE}" \ meta.helm.sh/release-name="${RELEASE_NAME}" \ meta.helm.sh/release-namespace="${NAMESPACE}" \ -n "${NAMESPACE}" --overwrite && \ kubectl label "${RESOURCE}" \ app.kubernetes.io/managed-by=Helm \ -n "${NAMESPACE}" --overwrite done ``` Do not annotate the headless service (`service/${CRDBCLUSTER}`). The headless service is operator-managed and not templated by the CockroachDB Helm chart. Do not annotate the migration-created ClusterRole/ClusterRoleBinding. The CockroachDB Helm chart creates its own cluster-scoped RBAC with different names (`{fullname}-{namespace}-node-reader`). Delete the stale migration-created role and binding after Helm adoption: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Migration-created ClusterRole/ClusterRoleBinding use "{namespace}-{name}" naming kubectl delete clusterrole ${NAMESPACE}-${CRDBCLUSTER} --ignore-not-found kubectl delete clusterrolebinding ${NAMESPACE}-${CRDBCLUSTER} --ignore-not-found ``` ### Transfer field ownership to Helm The public operator and migration controller write some fields on the Role and public Service using the `cockroach-operator` field manager. Helm uses the `Helm` field manager during server-side apply. Transfer ownership of those existing fields before Helm adoption to avoid conflict errors. This is metadata-only. This script does not delete or recreate resources and does not affect running pods. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} for RESOURCE in \ "role/${CRDBCLUSTER}" \ "service/${CRDBCLUSTER}-public"; do kubectl apply --server-side --force-conflicts --field-manager=Helm \ -f <(kubectl get "${RESOURCE}" -n "${NAMESPACE}" -o yaml) 2>/dev/null done ``` ### Run Helm install There is no existing Helm release for the migrated cluster, so use `--install` to create one. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade --install ${RELEASE_NAME} cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} \ --namespace ${NAMESPACE} \ --values your-values.yaml ``` Verify the install succeeded: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.metadata.labels.app\.kubernetes\.io/managed-by}' # Expected: Helm ``` After adoption is verified, consider performing a rolling restart to confirm chart-managed configuration is fully applied. Post-migration there is no StatefulSet, so trigger a rolling restart via `helm upgrade` with an updated timestamp: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade ${RELEASE_NAME} cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} \ --namespace ${NAMESPACE} \ --set cockroachdb.crdbCluster.timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ --values your-values.yaml ``` Verify generation matching to confirm the operator has reconciled: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.metadata.generation} {.status.observedGeneration}' # Both values should match ``` ### Update certificate mode after adoption After migration, all certificate references are stored as `externalCertificates` on the CrdbCluster spec, regardless of the original cert type. The `export-values` tool outputs these as `cockroachdb.tls.externalCertificates`. After Helm adoption, update your `values.yaml` to use the cert mode that matches your intended ongoing management: * **Self-signer**: Switch to `cockroachdb.tls.selfSigner.enabled: true` and remove the `externalCertificates` block. The operator's self-signer will manage cert rotation going forward. The migration-created `{name}-node-secret` and `{name}-client-secret` secrets become stale once the self-signer creates its own. Delete them after verifying the new certs are working. * **cert-manager**: Switch to `cockroachdb.tls.certManager.enabled: true` with the appropriate issuer reference. The migration preserved the Certificate CR and its `spec.secretName`, so cert-manager continues to manage rotation. Remove the `externalCertificates` block from values. * **User-provided / External**: Keep `cockroachdb.tls.externalCertificates` as exported. You are responsible for cert rotation. After updating cert mode, run `helm upgrade` again and verify pods are healthy. Clean up any stale secrets that are no longer referenced: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check which secrets are actually mounted by pods kubectl get pod $CRDBCLUSTER-0 -n $NAMESPACE -o jsonpath='{.spec.volumes[*].secret.secretName}' # Delete stale migration-created secrets if they are no longer mounted kubectl delete secret $CRDBCLUSTER-node-secret -n $NAMESPACE --ignore-not-found kubectl delete secret $CRDBCLUSTER-client-secret -n $NAMESPACE --ignore-not-found ``` ## Step 13: Patch storedVersions After all v1alpha1 clusters across the entire Kubernetes cluster have been migrated and the public operator has been removed, patch the CRD's `storedVersions` to remove v1alpha1. Do not do this until every v1alpha1 cluster has completed migration and the public operator is stopped. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Verify all clusters are migrated kubectl get crdbclusters --all-namespaces \ -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}: phase={.status.migration.phase}{"\n"}{end}' # Patch storedVersions kubectl patch crd crdbclusters.crdb.cockroachlabs.com \ --subresource=status \ --type=json \ -p='[{"op":"replace","path":"/status/storedVersions","value":["v1beta1"]}]' # Verify kubectl get crd crdbclusters.crdb.cockroachlabs.com \ -o jsonpath='{.status.storedVersions}' # Expected: ["v1beta1"] ``` ## Step 14: Disable migration mode (Optional) After `storedVersions` is patched, disabling migration mode is optional. When the operator restarts without the flag, it sees that `storedVersions` no longer contains v1alpha1 and sets v1alpha1 `served=false` on the CRD. The conversion webhook is removed. If you leave `migration.enabled=true` after patching `storedVersions`, the operator continues to register the conversion webhook and migration controller, but they have no effect. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} helm upgrade crdb-operator cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 \ --reuse-values \ --set migration.enabled=false ``` After this: * v1alpha1 is no longer served by the API server. * The conversion webhook is removed from the CRD. * All existing v1beta1 clusters continue working normally. > [!CAUTION] > > Do not disable migration mode while the public operator is still running or before `storedVersions` is patched. Disabling it removes the conversion webhook, which causes the API server to drop v1beta1-only fields (certificates, regions, podTemplate) from the stored CrdbCluster spec during v1alpha1 round-trips. ### Removing the CockroachDB operator If you uninstall the CockroachDB operator without completing steps 13-14 first, the CRD still has the conversion webhook pointing at a dead endpoint. Any v1alpha1 API calls (including `kubectl get crdbclusters` if the API server chooses v1alpha1 as the storage version) will fail with webhook connection errors. To recover: 1. Patch `storedVersions` to remove v1alpha1 (Step 13). 2. Remove the conversion webhook from the CRD manually: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl patch crd crdbclusters.crdb.cockroachlabs.com \ --type=json \ -p='[{"op":"remove","path":"/spec/conversion/webhook"},{"op":"replace","path":"/spec/conversion/strategy","value":"None"}]' ``` 3. Optionally remove v1alpha1 from the CRD's `spec.versions` if no v1alpha1 clusters remain. Always complete steps 13-14 before uninstalling the operator. ### Conversion annotations The conversion webhook writes annotations on v1alpha1 objects to preserve v1beta1 state across round-trips. `ConvertFrom` always refreshes the hub spec annotation from the current v1beta1 spec, so the annotation is always up to date when `ConvertTo` reads it. This ensures v1beta1-only fields like `ServiceAccountName` and `StartFlags` survive any v1alpha1 write-back. The migration controller strips these annotations on `Phase=Complete` as cleanup, but they are harmless and will be re-created if a v1alpha1 read occurs while the conversion webhook is still active. Disabling migration mode prevents any further round-trips. ## Troubleshooting Follow these troubleshooting steps if there are issues with the migration: ### Migration fails with "missing required label: crdb.io/skip-reconcile=true" The `skip-reconcile` label was not applied before starting migration. Apply it and retry: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label crdbcluster $CRDBCLUSTER crdb.io/skip-reconcile="true" -n $NAMESPACE kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=start --overwrite -n $NAMESPACE ``` ### Migration stuck at PodMigration phase If a node fails health checks for more than 10 minutes, migration auto-pauses to `PhaseStopped`. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check why migration stopped kubectl get crdbcluster $CRDBCLUSTER -n $NAMESPACE \ -o jsonpath='{.status.migration.lastError}' # Check pod status kubectl describe pod $CRDBCLUSTER- -n $NAMESPACE # Check CrdbNode status kubectl get crdbnode $CRDBCLUSTER- -n $NAMESPACE -o yaml # Resume after fixing kubectl label crdbcluster $CRDBCLUSTER crdb.io/migrate=start --overwrite -n $NAMESPACE ``` ### CrdbCluster not found For operator migrations, the v1beta1 CrdbCluster is created via the conversion webhook. The conversion webhook is only registered when the operator is started with `--enable-migration` (or `migration.enabled=true` in Helm). If the v1beta1 CrdbCluster is missing, ensure: * The CockroachDB operator was installed with `migration.enabled=true`. * The webhook service is running and reachable. * The v1alpha1 CrdbCluster has not been deleted. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check if conversion webhook is configured kubectl get crd crdbclusters.crdb.cockroachlabs.com -o yaml | grep -A5 conversion ``` ### Under-replicated ranges The controller retries health checks every 10 seconds. If under-replicated ranges persist for more than 10 minutes, migration auto-pauses. ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # StatefulSet pods use -c db. Migrated CrdbNode pods use -c cockroachdb. kubectl exec $CRDBCLUSTER-0 -n $NAMESPACE -c db -- \ /cockroach/cockroach sql --certs-dir=/cockroach/cockroach-certs \ -e "SELECT sum((metrics->>'ranges.underreplicated')::INT8) FROM crdb_internal.kv_store_status;" ``` ### RBAC conflicts between public and CockroachDB operator If both operators are fighting over RBAC, check the following: 1. Verify `skip-reconcile` is set on the v1alpha1 CrdbCluster. 2. Verify the CockroachDB Operator uses `watchNamespaces` to limit its scope. 3. Check that ClusterRole names do not collide (CockroachDB Operator uses `{namespace}-{name}`). ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Check namespace-scoped RBAC kubectl get role $CRDBCLUSTER -n $NAMESPACE kubectl get rolebinding $CRDBCLUSTER -n $NAMESPACE # Check cluster-scoped RBAC (namespace-qualified names) kubectl get clusterrole ${NAMESPACE}-${CRDBCLUSTER} kubectl get clusterrolebinding ${NAMESPACE}-${CRDBCLUSTER} ``` ### ConfigMap key format The public operator uses `logging.yaml` as the key in log-config ConfigMaps. The CockroachDB operator uses `logs.yaml`. The migration controller renames this key automatically. On rollback, the key is renamed back. Verify: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get configmap -n $NAMESPACE -o yaml | grep -E "logging.yaml|logs.yaml" ``` ### Operator fails with "storedVersions: must appear in spec.versions" You may see an error like: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} status.storedVersions[0]: Invalid value: "v1alpha1": must appear in spec.versions ``` This happens when the operator tries to remove v1alpha1 from `spec.versions`, but `status.storedVersions` still lists it. Kubernetes requires every stored version to remain in `spec.versions`. A common cause is removing `migration.enabled=true` before patching `storedVersions` in Step 13. Fix it by either re-enabling migration temporarily or patching `storedVersions` if all clusters are already migrated: ```bash theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Option 1: Re-enable migration temporarily helm upgrade crdb-operator cockroachdb-v2/cockroachdb-operator-chart --version 1.0.0 \ --reuse-values \ --set migration.enabled=true # Option 2: Patch storedVersions if all clusters are already migrated kubectl patch crd crdbclusters.crdb.cockroachlabs.com \ --subresource=status --type=json \ -p='[{"op":"replace","path":"/status/storedVersions","value":["v1beta1"]}]' ``` After patching, restart the operator without the migration flag as described in Step 14. ### Verifying v1alpha1 storage state Running `kubectl get crdbclusters.v1alpha1.crdb.cockroachlabs.com` does not prove that objects are still stored as v1alpha1. The conversion webhook can convert v1beta1 objects back to v1alpha1 on read. The reliable indicator is the CRD's `status.storedVersions` field, but this is a high-water mark. Kubernetes adds versions when objects have been stored in that version, but does not remove them automatically. A version listed in `storedVersions` means objects were stored in that version at some point, not necessarily that they still are. Before patching `storedVersions`: 1. Ensure the CockroachDB Operator has reconciled every CrdbCluster at least once. 2. Verify no public operator remains running. 3. Patch `storedVersions` as described in Step 13. # Cluster Monitoring Source: https://docs.cockroachlabs.com/docs/stable/monitor-cockroachdb-kubernetes > [!NOTE] > > This article assumes you have already [deployed CockroachDB on a single Kubernetes cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes). Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/architecture/replication-layer), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. This page is for Kubernetes deployments that are not using the CockroachDB operator. For guidance specific to the CockroachDB operator, read [Cluster Monitoring with the CockroachDB operator](/docs/v26.4/monitor-cockroachdb-operator). > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). > [!NOTE] > > All `kubectl` steps should be performed in the [namespace where you installed the operator](/docs/v26.4/deploy-cockroachdb-with-kubernetes#install-the-operator). By default, this is `cockroach-operator-system`. > [!TIP] > > If you [deployed CockroachDB on Red Hat OpenShift](/docs/v26.4/deploy-cockroachdb-with-kubernetes-openshift), substitute `kubectl` with `oc` in the following commands. ## Configure Prometheus Every node of a CockroachDB cluster exports granular timeseries metrics formatted for easy integration with [Prometheus](https://prometheus.io/), a tool for storing, aggregating, and querying timeseries data. This section shows you how to orchestrate Prometheus as part of your Kubernetes cluster and pull these metrics into Prometheus for external monitoring. This guidance is based on [CoreOS's Prometheus Operator](https://github.com/coreos/prometheus-operator/blob/master/Documentation/user-guides/getting-started.md), which allows a Prometheus instance to be managed using built-in Kubernetes concepts. > [!NOTE] > > If you're on Hosted GKE, before starting, make sure the email address associated with your Google Cloud account is part of the `cluster-admin` RBAC group, as shown in [Deploy CockroachDB with Kubernetes](/docs/v26.4/deploy-cockroachdb-with-kubernetes#hosted-gke). 1. From your local workstation, edit the `cockroachdb` service to add the `prometheus: cockroachdb` label: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl label svc cockroachdb prometheus=cockroachdb ``` ``` service/cockroachdb labeled ``` This ensures that only the `cockroachdb` (not the `cockroach-public` service) is being monitored by a Prometheus job. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl label svc cockroachdb prometheus=cockroachdb ``` ``` service/cockroachdb labeled ``` This ensures that only the `cockroachdb` (not the `cockroach-public` service) is being monitored by a Prometheus job. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl label svc my-release-cockroachdb prometheus=cockroachdb ``` ``` service/my-release-cockroachdb labeled ``` This ensures that there is a Prometheus job and monitoring data only for the `my-release-cockroachdb` service, not for the `my-release-cockroach-public` service. 2. Determine the latest version of [CoreOS's Prometheus Operator](https://github.com/prometheus-operator/prometheus-operator/releases/) and run the following to download and apply the latest `bundle.yaml` definition file: > [!NOTE] > > Be sure to specify the latest [CoreOS Prometheus Operator](https://github.com/prometheus-operator/prometheus-operator/releases/) version in the following command, in place of this example's use of version `v0.58.0`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply \ -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/v0.58.0/bundle.yaml \ --server-side ``` ``` customresourcedefinition.apiextensions.k8s.io/alertmanagers.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/podmonitors.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/probes.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/prometheuses.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/prometheusrules.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/servicemonitors.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/thanosrulers.monitoring.coreos.com serverside-applied clusterrolebinding.rbac.authorization.k8s.io/prometheus-operator serverside-applied clusterrole.rbac.authorization.k8s.io/prometheus-operator serverside-applied deployment.apps/prometheus-operator serverside-applied serviceaccount/prometheus-operator serverside-applied service/prometheus-operator serverside-applied ``` 1. Confirm that the `prometheus-operator` has started: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get deploy prometheus-operator ``` ``` NAME READY UP-TO-DATE AVAILABLE AGE prometheus-operator 1/1 1 1 27s ``` 2. Download our Prometheus manifest: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/prometheus.yaml ``` By default, this manifest uses the secret name generated by the Public operator. If you generated your own certificates and keys when [starting CockroachDB](/docs/v26.4/deploy-cockroachdb-with-kubernetes#step-2-start-cockroachdb), be sure that `ca.secret.name` matches the name of the node secret you created. 3. Apply the Prometheus manifest. This creates the various objects necessary to run a Prometheus instance: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f prometheus.yaml ``` ``` serviceaccount/prometheus created clusterrole.rbac.authorization.k8s.io/prometheus created clusterrolebinding.rbac.authorization.k8s.io/prometheus created servicemonitor.monitoring.coreos.com/cockroachdb created prometheus.monitoring.coreos.com/cockroachdb created ``` 4. Access the Prometheus UI locally and verify that CockroachDB is feeding data into Prometheus: 1. Port-forward from your local machine to the pod running Prometheus: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward prometheus-cockroachdb-0 9090 ``` 2. Go to [http://localhost:9090](http://localhost:9090) in your browser. 3. To verify that each CockroachDB node is connected to Prometheus, go to **Status > Targets**. The screen should look like this: ![Prometheus targets](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-targets.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=694a2390061f9933fcef1367f0b28884) 4. To verify that data is being collected, go to **Graph**, enter the `sys_uptime` variable in the field, click **Execute**, and then click the **Graph** tab. The screen should like this: ![Prometheus graph](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-graph.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=ebbcfb84e38e7b3e84688dc5f74aea75) > [!TIP] > > Prometheus auto-completes CockroachDB time series metrics for you, but if you want to see a full listing, with descriptions, port-forward as described in [Access the DB Console](/docs/v26.4/deploy-cockroachdb-with-kubernetes#step-4-access-the-db-console)[Access the DB Console](/docs/v26.4/deploy-cockroachdb-with-kubernetes#step-4-access-the-db-console) and then point your browser to the [Prometheus endpoint](/docs/v26.4/prometheus-endpoint). > > For more details on using the Prometheus UI, see their [official documentation](https://prometheus.io/docs/introduction/getting_started/). ## Configure Alertmanager Active monitoring helps you spot problems early, but it is also essential to send notifications when there are events that require investigation or intervention. This section shows you how to use [Alertmanager](https://prometheus.io/docs/alerting/alertmanager/) and CockroachDB's starter [alerting rules](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alert-rules.yaml) to do this. 1. Download our `alertmanager-config.yaml` configuration file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O \ https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager-config.yaml ``` 2. Edit the `alertmanager-config.yaml` file to [specify the desired receivers for notifications](https://prometheus.io/docs/alerting/configuration/#receiver). Initially, the file contains a placeholder web hook. 3. Add this configuration to the Kubernetes cluster as a secret, renaming it to `alertmanager.yaml` and labelling it to make it easier to find: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create secret generic alertmanager-cockroachdb \ --from-file=alertmanager.yaml=alertmanager-config.yaml ``` ``` secret/alertmanager-cockroachdb created ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl label secret alertmanager-cockroachdb app=cockroachdb ``` ``` secret/alertmanager-cockroachdb labeled ``` > [!CAUTION] > > The name of the secret, `alertmanager-cockroachdb`, must match the name used in the `alertmanager.yaml` file. If they differ, the Alertmanager instance will start without configuration, and nothing will happen. 1. Use our [`alertmanager.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager.yaml) file to create the various objects necessary to run an Alertmanager instance, including a ClusterIP service so that Prometheus can forward alerts: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply \ -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager.yaml ``` ``` alertmanager.monitoring.coreos.com/cockroachdb created service/alertmanager-cockroachdb created ``` 2. Verify that Alertmanager is running: 1. Port-forward from your local machine to the pod running Alertmanager: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward alertmanager-cockroachdb-0 9093 ``` 2. Go to [http://localhost:9093](http://localhost:9093) in your browser. The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-alertmanager-home.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=b2ab783f1a68700e9f2ce40cdbf655b5) 3. Ensure that the Alertmanagers are visible to Prometheus by opening [http://localhost:9090/status](http://localhost:9090/status). The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-alertmanagers.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=e47e75c7fa1fff9566d7f0cf046583bc) 4. Add CockroachDB's starter [alerting rules](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alert-rules.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply \ -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alert-rules.yaml ``` ``` prometheusrule.monitoring.coreos.com/prometheus-cockroachdb-rules created ``` 5. Ensure that the rules are visible to Prometheus by opening [http://localhost:9090/rules](http://localhost:9090/rules). The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-alertrules.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=2ac025152cd19e9bbdce56ba3e6ad3ff) 6. Verify that the `TestAlertManager` example alert is firing by opening [http://localhost:9090/alerts](http://localhost:9090/alerts). The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-alerts.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=e6dee328d4a37b3dd2a4db1c39fc0405) 7. To remove the example alert: 1. Use the `kubectl edit` command to open the rules for editing: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl edit prometheusrules prometheus-cockroachdb-rules ``` 2. Remove the `dummy.rules` block and save the file: ``` - name: rules/dummy.rules rules: - alert: TestAlertManager expr: vector(1) ``` ## Configure logging When running CockroachDB v21.1 and later, you can use the Public operator to configure the CockroachDB logging system. This allows you to output logs to [configurable log sinks](/docs/v26.4/configure-logs#configure-log-sinks) such as file or network logging destinations. > [!NOTE] > > By default, Kubernetes deployments running CockroachDB v20.2 or earlier output all logs to `stderr`. The logging configuration is defined in a [ConfigMap](https://kubernetes.io/docs/concepts/configuration/configmap/) object, using a key named `logging.yaml`. For example: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: v1 data: logging.yaml: | sinks: file-groups: dev: channels: DEV filter: WARNING fluent-servers: ops: channels: [OPS, HEALTH, SQL_SCHEMA] address: 127.0.0.1:5170 net: tcp redact: true security: channels: [SESSIONS, USER_ADMIN, PRIVILEGES, SENSITIVE_ACCESS] address: 127.0.0.1:5170 net: tcp auditable: true kind: ConfigMap metadata: name: logconfig namespace: cockroach-operator-system ``` The above configuration overrides the [default logging configuration](/docs/v26.4/configure-logs#default-logging-configuration) and reflects our recommended Kubernetes logging configuration: * Save debug-level logs (the `DEV` [log channel](/docs/v26.4/logging-overview#logging-channels)) to disk for troubleshooting. * Send operational- and security-level logs to a [network collector](/docs/v26.4/logging-use-cases#network-logging), in this case [Fluentd](/docs/v26.4/configure-logs#fluentd-logging-format). The ConfigMap `name` must match the `logConfigMap` object of the Public operator's custom resource, which is used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: logConfigMap: logconfig ``` By default, the Public operator also modifies the [default logging configuration](/docs/v26.4/configure-logs#default-logging-configuration) with the following: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} sinks: stderr: channels: OPS redact: true ``` This outputs logging events in the [`OPS`](/docs/v26.4/logging#ops) channel to a `cockroach-stderr.log` file. ### Example: Creating a troubleshooting log file on pods In this example, CockroachDB has already been deployed on a Kubernetes cluster. We override the [default logging configuration](/docs/v26.4/configure-logs#default-logging-configuration) to output [`DEV`](/docs/v26.4/logging#dev) logs to a `cockroach-dev.log` file. 1. Create a ConfigMap named `logconfig`. Note that `namespace` is set to the Public operator's default namespace (`cockroach-operator-system`): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: v1 data: logging.yaml: | sinks: file-groups: dev: channels: DEV filter: WARNING kind: ConfigMap metadata: name: logconfig namespace: cockroach-operator-system ``` For simplicity, also name the YAML file `logconfig.yaml`. > [!NOTE] > > The ConfigMap key is not related to the ConfigMap `name` or YAML filename, and **must** be named `logging.yaml`. This configuration outputs `DEV` logs that have severity [`WARNING`](/docs/v26.4/logging#logging-levels-severities) to a `cockroach-dev.log` file on each pod. 1. Apply the ConfigMap to the cluster: ``` kubectl apply -f logconfig.yaml ``` ``` configmap/logconfig created ``` 2. Add the `name` of the ConfigMap in `logConfigMap` to the [Public operator's custom resource](/docs/v26.4/deploy-cockroachdb-with-kubernetes#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} spec: logConfigMap: logconfig ``` 3. Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl apply -f example.yaml ``` The changes will be rolled out to each pod. 4. See the log files available on a pod: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec cockroachdb-2 -- ls cockroach-data/logs ``` ``` cockroach-dev.cockroachdb-2.unknownuser.2022-05-02T19_03_03Z.000001.log cockroach-dev.log cockroach-health.cockroachdb-2.unknownuser.2022-05-02T18_53_01Z.000001.log cockroach-health.log cockroach-pebble.cockroachdb-2.unknownuser.2022-05-02T18_52_48Z.000001.log cockroach-pebble.log cockroach-stderr.cockroachdb-2.unknownuser.2022-05-02T18_52_48Z.000001.log cockroach-stderr.cockroachdb-2.unknownuser.2022-05-02T19_03_03Z.000001.log cockroach-stderr.cockroachdb-2.unknownuser.2022-05-02T20_04_03Z.000001.log cockroach-stderr.log cockroach.cockroachdb-2.unknownuser.2022-05-02T18_52_48Z.000001.log cockroach.log ... ``` 5. View a specific log file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec cockroachdb-2 -- cat cockroach-data/logs/cockroach-dev.log ``` ## See also * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Metrics](/docs/v26.4/metrics) # Cluster Monitoring with the CockroachDB Operator Source: https://docs.cockroachlabs.com/docs/stable/monitor-cockroachdb-operator Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/architecture/replication-layer), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. ## Configure Prometheus Every node of a CockroachDB cluster exports granular timeseries metrics formatted for easy integration with [Prometheus](https://prometheus.io/), a tool for storing, aggregating, and querying timeseries data. This section shows you how to orchestrate Prometheus as part of your Kubernetes cluster and pull these metrics into Prometheus for external monitoring. This guidance is based on [CoreOS's Prometheus Operator](https://github.com/prometheus-operator/prometheus-operator/tree/main), which allows a Prometheus instance to be managed using built-in Kubernetes concepts. > [!NOTE] > > If you're on Hosted GKE, before starting, make sure the email address associated with your Google Cloud account is part of the `cluster-admin` RBAC group, as shown in [Deploy CockroachDB with Kubernetes](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator). 1. From your local workstation, edit the cockroachdb service to add the prometheus: cockroachdb label: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label svc cockroachdb prometheus=cockroachdb ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} service/cockroachdb labeled ``` This ensures that only the cockroachdb (not the cockroach-public service) is being monitored by a Prometheus job. 2. Determine the latest version of [CoreOS's Prometheus Operator](https://github.com/prometheus-operator/prometheus-operator/releases/) and run the following to download and apply the latest `bundle.yaml` definition file: > [!NOTE] > > Be sure to specify the latest [CoreOS Prometheus Operator](https://github.com/prometheus-operator/prometheus-operator/releases/) version in the following command, in place of this example's use of version `v0.82.0`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply \ -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/v0.82.0/bundle.yaml \ --server-side ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} customresourcedefinition.apiextensions.k8s.io/alertmanagers.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/podmonitors.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/probes.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/prometheuses.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/prometheusrules.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/servicemonitors.monitoring.coreos.com serverside-applied customresourcedefinition.apiextensions.k8s.io/thanosrulers.monitoring.coreos.com serverside-applied clusterrolebinding.rbac.authorization.k8s.io/prometheus-operator serverside-applied clusterrole.rbac.authorization.k8s.io/prometheus-operator serverside-applied deployment.apps/prometheus-operator serverside-applied serviceaccount/prometheus-operator serverside-applied service/prometheus-operator serverside-applied ``` 1. Confirm that the `prometheus-operator` has started: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get deploy prometheus-operator ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} NAME READY UP-TO-DATE AVAILABLE AGE prometheus-operator 1/1 1 1 27s ``` 2. Download our Prometheus manifest: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/prometheus.yaml ``` 3. Apply the Prometheus manifest. This creates the various objects necessary to run a Prometheus instance: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f prometheus.yaml ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} serviceaccount/prometheus created clusterrole.rbac.authorization.k8s.io/prometheus created clusterrolebinding.rbac.authorization.k8s.io/prometheus created servicemonitor.monitoring.coreos.com/cockroachdb created prometheus.monitoring.coreos.com/cockroachdb created ``` 4. Access the Prometheus UI locally and verify that CockroachDB is feeding data into Prometheus: 1. Port-forward from your local machine to the pod running Prometheus: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl port-forward prometheus-cockroachdb-0 9090 ``` 2. Go to [http://localhost:9090](http://localhost:9090/) in your browser. 3. To verify that each CockroachDB node is connected to Prometheus, go to **Status > Targets**. The screen should look like this: ![Prometheus targets](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-targets.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=694a2390061f9933fcef1367f0b28884) 4. To verify that data is being collected, go to **Graph**, enter the `sys_uptime` variable in the field, click **Execute**, and then click the **Graph** tab. The screen should like this: ![Prometheus graph](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-graph.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=ebbcfb84e38e7b3e84688dc5f74aea75) > [!NOTE] > > Prometheus auto-completes CockroachDB time series metrics for you, but if you want to see a full listing, with descriptions, port-forward as described in [Access the DB Console](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#step-4-access-the-db-console) and then point your browser to [http://localhost:8080/\_status/vars](http://localhost:8080/_status/vars). For more details on using the Prometheus UI, see their [official documentation](https://prometheus.io/docs/introduction/getting_started/). ## Configure Alertmanager Active monitoring helps you spot problems early, but it is also essential to send notifications when there are events that require investigation or intervention. This section shows you how to use [Alertmanager](https://prometheus.io/docs/alerting/alertmanager/) and CockroachDB's starter [alerting rules](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alert-rules.yaml) to do this. 1. Download our [alertmanager-config.yaml](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager-config.yaml) configuration file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager-config.yaml ``` 2. Edit the `alertmanager-config.yaml` file to [specify the desired receivers for notifications](https://prometheus.io/docs/alerting/configuration/#receiver). Initially, the file contains a placeholder web hook. 3. Add this configuration to the Kubernetes cluster as a secret, renaming it to `alertmanager.yaml` and labeling it to make it easier to find: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create secret generic alertmanager-cockroachdb \ --from-file=alertmanager.yaml=alertmanager-config.yaml ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} secret/alertmanager-cockroachdb created ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl label secret alertmanager-cockroachdb app=cockroachdb ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} secret/alertmanager-cockroachdb labeled ``` > [!CAUTION] > > The name of the secret, `alertmanager-cockroachdb`, must match the name used in the `alertmanager.yaml` file. If they differ, the Alertmanager instance will start without configuration, and nothing will happen. 1. Use our [alertmanager.yaml](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager.yaml) file to create the various objects necessary to run an Alertmanager instance, including a ClusterIP service so that Prometheus can forward alerts: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply \ -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alertmanager.yaml ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} alertmanager.monitoring.coreos.com/cockroachdb created service/alertmanager-cockroachdb created ``` 2. Verify that Alertmanager is running: 1. Port-forward from your local machine to the pod running Alertmanager: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl port-forward alertmanager-cockroachdb-0 9093 ``` 2. Go to [http://localhost:9093](http://localhost:9093/) in your browser. The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-alertmanager-home.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=b2ab783f1a68700e9f2ce40cdbf655b5) 3. Ensure that the Alertmanagers are visible to Prometheus by opening [http://localhost:9090/status](http://localhost:9090/status). The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-alertmanagers.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=e47e75c7fa1fff9566d7f0cf046583bc) 4. Add CockroachDB's starter [alerting rules](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alert-rules.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply \ -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/prometheus/alert-rules.yaml ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} prometheusrule.monitoring.coreos.com/prometheus-cockroachdb-rules created ``` 5. Ensure that the rules are visible to Prometheus by opening [http://localhost:9090/rules](http://localhost:9090/rules). The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-alertrules.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=2ac025152cd19e9bbdce56ba3e6ad3ff) 6. Verify that the `TestAlertManager` example alert is firing by opening [http://localhost:9090/alerts](http://localhost:9090/alerts). The screen should look like this: ![Alertmanager](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/kubernetes-prometheus-alerts.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=e6dee328d4a37b3dd2a4db1c39fc0405) 7. To remove the example alert: 1. Use the `kubectl edit` command to open the rules for editing: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl edit prometheusrules prometheus-cockroachdb-rules ``` 2. Remove the `dummy.rules` block and save the file: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} - name: rules/dummy.rules rules: - alert: TestAlertManager expr: vector(1) ``` ## Monitor the operator The CockroachDB operator automatically exposes [Prometheus-style metrics](https://prometheus.io/docs/concepts/metric_types/) that you can monitor to observe its operations. Metrics can be collected from the operator via HTTP requests (port 8080 by default) against the `/metrics` endpoint. The response will describe the current node metrics, for example: ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ... # HELP node_decommissioning Whether a CockroachDB node is decommissioning. # TYPE node_decommissioning gauge node_decommissioning{node="cockroachdb-nvq2l"} 0 node_decommissioning{node="cockroachdb-pmp45"} 0 node_decommissioning{node="cockroachdb-q6784"} 0 node_decommissioning{node="cockroachdb-r4wz8"} 0 ... ``` ## Configure logging You can use the operator to configure the CockroachDB logging system. This allows you to output logs to [configurable log sinks](/docs/v26.4/configure-logs#configure-log-sinks) such as file or network logging destinations. The logging configuration is defined in a [ConfigMap](https://kubernetes.io/docs/concepts/configuration/configmap/) object, using a key named `logs.yaml`. For example: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: v1 data: logs.yaml: | sinks: file-groups: dev: channels: DEV filter: WARNING kind: ConfigMap metadata: name: logconfig namespace: cockroach-ns ``` The above configuration overrides the [default logging configuration](/docs/v26.4/configure-logs#default-logging-configuration) and saves debug-level logs (the `DEV` [log channel](/docs/v26.4/logging-overview#logging-channels)) to disk for troubleshooting. The ConfigMap `name` must match the `cockroachdb.crdbCluster.loggingConfigMapName` object in the values file used to [deploy the cluster](/docs/v26.4/deploy-cockroachdb-with-cockroachdb-operator#initialize-the-cluster): ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: loggingConfigMapName: logconfig ``` By default, the operator also modifies the [default logging configuration](/docs/v26.4/configure-logs#default-logging-configuration) with the following: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} sinks: stderr: channels: {INFO: "HEALTH, OPS", WARNING: "STORAGE, DEV"} redact: true ``` This outputs logging events in the [OPS](/docs/v26.4/logging#ops) channel to a `cockroach-stderr.log` file. ### Example: Configuring a troubleshooting log file on pods In this example, CockroachDB has already been deployed on a Kubernetes cluster. Override the [default logging configuration](/docs/v26.4/configure-logs#default-logging-configuration) to output [DEV](/docs/v26.4/logging#dev) logs to a `cockroach-dev.log` file. 1. Create a ConfigMap named `logconfig`. Note that `namespace` is set to the `cockroach-ns` namespace: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} apiVersion: v1 data: logs.yaml: | sinks: file-groups: dev: channels: DEV filter: WARNING kind: ConfigMap metadata: name: logconfig namespace: cockroach-ns ``` For simplicity, also name the YAML file `logconfig.yaml`. > [!NOTE] > > The ConfigMap key is not related to the ConfigMap `name` or YAML filename, and must be named `logging.yaml`. This configuration outputs `DEV` logs that have severity [WARNING](/docs/v26.4/logging#logging-levels-severities) to a `cockroach-dev.log` file on each pod. 1. Apply the ConfigMap to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f logconfig.yaml ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} configmap/logconfig created ``` 2. Add the `name` of the ConfigMap in `loggingConfigMapName` to the values file: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: loggingConfigMapName: logconfig ``` 3. Apply the new settings to the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} # Generate values.yaml only if it does not already exist locally, then edit it before upgrading [ -f values.yaml ] || helm show values cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} > values.yaml # Apply the edited values.yaml helm upgrade $CRDBCLUSTER cockroachdb-v2/cockroachdb-chart --version {CHART_VERSION} -f values.yaml -n $NAMESPACE ``` The changes will be rolled out to each pod. 4. See the log files available on a pod: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl exec cockroachdb-2 -- ls cockroach-data/logs ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach-dev.cockroachdb-2.unknownuser.2022-05-02T19_03_03Z.000001.log cockroach-dev.log cockroach-health.cockroachdb-2.unknownuser.2022-05-02T18_53_01Z.000001.log cockroach-health.log cockroach-pebble.cockroachdb-2.unknownuser.2022-05-02T18_52_48Z.000001.log cockroach-pebble.log cockroach-stderr.cockroachdb-2.unknownuser.2022-05-02T18_52_48Z.000001.log cockroach-stderr.cockroachdb-2.unknownuser.2022-05-02T19_03_03Z.000001.log cockroach-stderr.cockroachdb-2.unknownuser.2022-05-02T20_04_03Z.000001.log cockroach-stderr.log cockroach.cockroachdb-2.unknownuser.2022-05-02T18_52_48Z.000001.log cockroach.log ... ``` 5. View a specific log file: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl exec cockroachdb-2 -- cat cockroach-data/logs/cockroach-dev.log ``` # Monitor CockroachDB with Prometheus Source: https://docs.cockroachlabs.com/docs/stable/monitor-cockroachdb-with-prometheus CockroachDB generates detailed time series metrics for each node in a cluster. This page shows you how to pull these metrics into [Prometheus](https://prometheus.io/), a tool for storing, aggregating, and querying time series data. It also shows you how to connect [Grafana](https://grafana.com/) and [Alertmanager](https://prometheus.io/docs/alerting/alertmanager/) to Prometheus for flexible data visualizations and notifications. This tutorial explores the CockroachDB integration with Prometheus. For the CockroachDB Advanced integration with Prometheus, refer to [Export Metrics From a CockroachDB Advanced Cluster](/docs/cockroachcloud/export-metrics-advanced?filters=prometheus-metrics-export) instead of this page. ## Before you begin * Make sure you have already started a CockroachDB cluster, either [locally](/docs/v26.4/start-a-local-cluster) or in a [production environment](/docs/v26.4/manual-deployment). ## Step 1. Install Prometheus 1. Download the [2.x Prometheus tarball](https://prometheus.io/download/) for your OS. 2. Extract the binary and add it to your system `PATH`. This makes it easy to start Prometheus from any shell. 3. Make sure Prometheus installed successfully: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ prometheus --version ``` ``` prometheus, version 2.34.0 (branch: HEAD, revision: 881111fec4332c33094a6fb2680c71fffc427275) build user: root@d80b449ae319 build date: 20220315-15:04:36 go version: go1.17.8 ``` ## Step 2. Configure Prometheus 1. Download the starter [Prometheus configuration file](https://docs.cockroachlabs.com/files/cockroach/monitoring/prometheus.yaml) for CockroachDB: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -o prometheus.yml https://docs.cockroachlabs.com/files/cockroach/monitoring/prometheus.yaml ``` When you examine the configuration file, you'll see that it is set up to scrape the time series metrics of a single, insecure local node every 10 seconds: * `scrape_interval: 10s` defines the scrape interval. * `metrics_path: '/_status/vars'` defines the Prometheus-specific CockroachDB endpoint for scraping time series metrics. * `scheme: 'http'` specifies that the cluster being scraped is insecure. * `targets: ['localhost:8080']` specifies the hostname and `http-port` of the Cockroach node to collect time series metrics on. 2. Edit the configuration file to match your deployment scenario: | Scenario | Config Change | | - | - | | Multi-node local cluster | Expand the `targets` field to include `'localhost: [!NOTE] > > If the cluster becomes unavailable, the DB Console and Cluster API will also become unavailable. You can continue to monitor the cluster via the [Prometheus endpoint](/docs/v26.4/prometheus-endpoint) and [logs](/docs/v26.4/logging-overview). ## Built-in monitoring tools CockroachDB includes several tools to help you monitor your cluster's workloads and performance. > [!CAUTION] > > If a cluster becomes unavailable, most of the monitoring tools in the following sections become unavailable. In that case, Cockroach Labs recommends that you consult the [cluster logs](/docs/v26.4/logging-overview). To maintain access to a cluster's historical metrics when the cluster is unavailable, configure a [third-party monitoring tool](/docs/v26.4/third-party-monitoring-tools) like Prometheus or Datadog to collect metrics periodically from the [Prometheus endpoint](/docs/v26.4/prometheus-endpoint). The metrics are stored outside the cluster, and can be used to help troubleshoot what led up to an outage. ### DB Console The [DB Console](/docs/v26.4/ui-overview) collects time-series cluster metrics and displays basic information about a cluster's health, such as node status, number of unavailable ranges, and queries per second and service latency across the cluster. This tool is designed to help you optimize cluster performance and troubleshoot issues. The DB Console is accessible from every node at `http:// [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). [Active Session History (ASH)](/docs/v26.4/active-session-history) is a time-series sampling-based observability feature that captures what work was actively executing on your cluster at specific points in time. Unlike the SQL Activity pages that aggregate data over time, ASH provides point-in-time snapshots of active execution, making it easier to diagnose transient performance problems and understand resource usage patterns. ASH is accessible via SQL queries against the [`information_schema.crdb_node_active_session_history`](/docs/v26.4/information-schema#crdb_node_active_session_history) and [`information_schema.crdb_cluster_active_session_history`](/docs/v26.4/information-schema#crdb_cluster_active_session_history) views. It is enabled and configurable via [cluster settings](/docs/v26.4/active-session-history#configuration). For more information, refer to [Active Session History](/docs/v26.4/active-session-history). ### Cluster API The [Cluster API](/docs/v26.4/cluster-api) is a REST API that runs in the cluster and provides much of the same information about your cluster and nodes as is available from the [DB Console](#db-console) or the [Prometheus endpoint](/docs/v26.4/prometheus-endpoint), and is accessible from each node at the same address and port as the DB Console. If the cluster is unavailable, the Cluster API is also unavailable. For more information, see the Cluster API [overview](/docs/v26.4/cluster-api) and [reference](/docs/api/cluster/index). ### `crdb_internal` system catalog The `crdb_internal` system catalog is a schema in each database that contains information about internal objects, processes, and metrics about that database. [DBMarlin](https://docs.dbmarlin.com/docs/Monitored-Technologies/Databases/cockroachdb) provides a third-party tool that collects metrics from a cluster's `crdb_internal` system catalogs rather than the cluster's Prometheus endpoint. If the cluster is unavailable, a database's `crdb_internal` system catalog cannot be queried. For details, see [`crdb_internal`](/docs/v26.4/crdb-internal). ### `information_schema` health tables The [`information_schema`](/docs/v26.4/information-schema) system catalog includes tables that report the state of nodes, stores, ranges, databases, tables, and indexes in stable, typed columns: * [`crdb_nodes`](/docs/v26.4/information-schema#crdb_nodes) * [`crdb_stores`](/docs/v26.4/information-schema#crdb_stores) * [`crdb_ranges`](/docs/v26.4/information-schema#crdb_ranges) * [`crdb_databases`](/docs/v26.4/information-schema#crdb_databases) * [`crdb_tables`](/docs/v26.4/information-schema#crdb_tables) * [`crdb_indexes`](/docs/v26.4/information-schema#crdb_indexes) Unlike most tables in the [`crdb_internal` system catalog](#crdb_internal-system-catalog), these tables are supported for production use and can be queried when the [`allow_unsafe_internals`](/docs/v26.4/session-variables#allow-unsafe-internals) session variable is `off`. Use them to check cluster health from SQL scripts and monitoring tools. `crdb_nodes` reads node status from the cluster's key-value layer, so it cannot be queried while the cluster is unavailable. For example queries, refer to [Check cluster health](/docs/v26.4/information-schema#check-cluster-health). ### Authenticate to API endpoints To call the HTTP API endpoints on this page using `curl`: For an insecure or local testing cluster, use HTTP: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl http://{host}:{http-port}/{endpoint} ``` For a secure cluster, authenticate to the HTTPS endpoint with [`cockroach auth-session login`](/docs/v26.4/cockroach-auth-session#log-in-to-the-http-interface), then pass the authentication cookie to `curl`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach auth-session login --certs-dir=certs --only-cookie > $HOME/.cockroachdb_api_key curl --cookie $HOME/.cockroachdb_api_key --cacert certs/ca.crt https://{host}:{http-port}/{endpoint} ``` ### Health endpoints CockroachDB provides two HTTP endpoints for checking the health of individual nodes. These endpoints are also available through the [Cluster API](/docs/v26.4/cluster-api) under `/v2/health/`. If the cluster is unavailable, these endpoints are also unavailable. #### /health If a node is down, the `http:// [!TIP] > > If you find that your load balancer's health check is not always recognizing a node as unready before the node shuts down, you can increase the `server.shutdown.initial_wait` [cluster setting](/docs/v26.4/cluster-settings) (previously named `server.shutdown.drain_wait`) to cause a node to return `503 Service Unavailable` even before it has started shutting down. * The node is [decommissioning or decommissioned](/docs/v26.4/node-shutdown?filters=decommission#decommissioning). This causes load balancers and connection managers to reroute traffic to other nodes while replicas are rebalanced away from the node. * The node is unable to communicate with a majority of the other nodes in the cluster, likely because the cluster is unavailable due to too many nodes being down. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -i http://localhost:8080/health?ready=1 ``` The `-i` flag includes the HTTP response status in the `curl` output. Without `-i`, `curl` prints only the response body by default. ``` HTTP/1.1 503 Service Unavailable { "error": "node is not healthy", "code": 14, "message": "node is not healthy", "details": [ ] } ``` Otherwise, it returns an HTTP `200 OK` status response code with an empty body: ``` { } ``` ### Raw status endpoints > [!NOTE] > > The JSON endpoints are deprecated in favor of the [Cluster API](#cluster-api). > > The `/_status/vars` metrics endpoint is in Prometheus format and is not deprecated. For more information, refer to [Prometheus endpoint](/docs/v26.4/prometheus-endpoint). Several endpoints return raw status meta information in JSON at `http:// [!NOTE] > > You may have to wait a few minutes after setting the database regions before getting the 'all clear' output above. This can happen because it takes time for [replica movement](/docs/v26.4/architecture/replication-layer) to occur in order to meet the constraints given by the [multi-region SQL abstractions](/docs/v26.4/multiregion-overview). ##### Replication status - constraint violation The following example assumes you are running a newly started, local multi-region [`cockroach demo`](/docs/v26.4/cockroach-demo) cluster started using the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach demo --global --nodes 9 --insecure ``` Execute the following statements to set the [database regions](/docs/v26.4/multiregion-overview#database-regions) for the [`movr` database](/docs/v26.4/movr#the-movr-database): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE movr SET PRIMARY REGION "us-east1"; ALTER DATABASE movr ADD REGION "us-west1"; ALTER DATABASE movr ADD REGION "europe-west1"; ``` By default, this multi-region demo cluster will not have any constraint violations. To introduce a violation that you can then query for, you'll [set the table locality to `REGIONAL BY TABLE`](/docs/v26.4/alter-table#set-the-table-locality-to-regional-by-table) for the [`movr.users`](/docs/v26.4/movr#the-movr-database) table. You can use [`SHOW CREATE TABLE`](/docs/v26.4/show-create) to see what existing [table locality](/docs/v26.4/table-localities) is attached to the `users` table, so you know what to modify. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SHOW CREATE TABLE users; ``` ``` table_name | create_statement -------------+----------------------------------------------------------- users | CREATE TABLE public.users ( | id UUID NOT NULL, | city VARCHAR NOT NULL, | name VARCHAR NULL, | address VARCHAR NULL, | credit_card VARCHAR NULL, | CONSTRAINT users_pkey PRIMARY KEY (city ASC, id ASC) | ) LOCALITY REGIONAL BY TABLE IN PRIMARY REGION (1 row) ``` To create a constraint violation, use the [`ALTER TABLE ... SET LOCALITY`](/docs/v26.4/alter-table#set-the-table-locality-to-regional-by-table) statement to tell the [ranges](/docs/v26.4/architecture/overview#architecture-range) in the `PRIMARY REGION` (`us-east1`) that they are supposed to be in the `europe-west1` locality: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER TABLE users SET LOCALITY REGIONAL BY TABLE IN "europe-west1"; ``` Once the statement above executes, the ranges currently stored in the `us-east1` locality will now be in a state where they are explicitly now supposed to be in the `europe-west1` locality, and are thus in violation of a constraint. In other words, this tells the ranges that "where you are now is *not* where you are supposed to be". This will cause the cluster to rebalance the ranges, which will take some time. During the time it takes for the rebalancing to occur, the ranges will be in violation of a constraint. The critical nodes endpoint should now report a constraint violation in the `violatingConstraints` field of the response, similar to the one shown below. > [!TIP] > > Use the [`SHOW RANGES`](/docs/v26.4/show-ranges) statement to find out more information about the ranges that are in violation of constraints. > > In a real life constraint violation scenario, you will need to [Troubleshoot your replication zones](/docs/v26.4/troubleshoot-replication-zones). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -X POST http://localhost:8080/_status/critical_nodes ``` ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "criticalNodes": [ ], "report": { "underReplicated": [ ], "overReplicated": [ ], "violatingConstraints": [ { "rangeDescriptor": { "rangeId": "71", "startKey": "8okSYW1zdGVyZGFtAAESszMzMzMzQAD/gAD/AP8A/wD/AP8A/yMAAQ==", "endKey": "8okSYm9zdG9uAAESMzMzMzMzRAD/gAD/AP8A/wD/AP8A/woAAQ==", "internalReplicas": [ { "nodeId": 8, "storeId": 8, "replicaId": 9, "type": 0 }, { "nodeId": 7, "storeId": 7, "replicaId": 8, "type": 0 }, { "nodeId": 1, "storeId": 1, "replicaId": 7, "type": 5 }, { "nodeId": 2, "storeId": 2, "replicaId": 5, "type": 0 }, { "nodeId": 6, "storeId": 6, "replicaId": 6, "type": 5 } ], "nextReplicaId": 10, "generation": "32", "stickyBit": { "wallTime": "9223372036854775807", "logical": 2147483647, "synthetic": false } }, "config": { "rangeMinBytes": "134217728", "rangeMaxBytes": "536870912", "gcPolicy": { "ttlSeconds": 14400, "protectionPolicies": [ ], "ignoreStrictEnforcement": false }, "globalReads": false, "numReplicas": 5, "numVoters": 3, "constraints": [ { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "europe-west1" } ] }, { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] }, { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "us-west1" } ] } ], "voterConstraints": [ { "numReplicas": 0, "constraints": [ { "type": 0, "key": "region", "value": "europe-west1" } ] } ], "leasePreferences": [ { "constraints": [ { "type": 0, "key": "region", "value": "europe-west1" } ] } ], "rangefeedEnabled": false, "excludeDataFromBackup": false } }, ... ], "unavailable": [ ], "unavailableNodeIds": [ ] } } ``` ##### Replication status - under-replicated ranges The following example assumes you are running a newly started, local multi-region [`cockroach demo`](/docs/v26.4/cockroach-demo) cluster started using the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach demo --global --nodes 9 --insecure ``` Execute the following statements to set the [database regions](/docs/v26.4/multiregion-overview#database-regions) for the [`movr` database](/docs/v26.4/movr#the-movr-database): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE movr SET PRIMARY REGION "us-east1"; ALTER DATABASE movr ADD REGION "us-west1"; ALTER DATABASE movr ADD REGION "europe-west1"; ``` By default, this multi-region demo cluster will not have any [under-replicated ranges](/docs/v26.4/ui-replication-dashboard#under-replicated-ranges). To put the cluster into a state where some [ranges](/docs/v26.4/architecture/overview#architecture-range) are under-replicated, issue the following [`ALTER DATABASE ... ALTER LOCALITY ... CONFIGURE ZONE`](/docs/v26.4/alter-database#alter-locality) statement, which tells it to store 9 copies of each range underlying the `movr` database. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE movr ALTER LOCALITY REGIONAL IN "us-east1" CONFIGURE ZONE USING num_replicas = 9; ``` Once the statement above executes, the cluster will rebalance so that it's storing 9 copies of each range underlying the `movr` database. During the time it takes for the rebalancing to occur, these ranges will be considered under-replicated, since there are not yet as many copies (9) of each range as you have just specified. The critical nodes endpoint should now report ranges in the `underReplicated` field of the response, similar to the one shown below. > [!TIP] > > Use the [`SHOW RANGES`](/docs/v26.4/show-ranges) statement to find out more information about the under-replicated ranges. > > In a real life under-replication scenario, you may need to [Troubleshoot your replication zones](/docs/v26.4/troubleshoot-replication-zones). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -X POST http://localhost:8080/_status/critical_nodes ``` ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "criticalNodes": [ { "nodeId": 3, "address": { "networkField": "tcp", "addressField": "127.0.0.1:26359" }, "attrs": { "attrs": [ ] }, "locality": { "tiers": [ { "key": "region", "value": "us-east1" }, { "key": "az", "value": "d" } ] }, "ServerVersion": { "majorVal": 23, "minorVal": 2, "patch": 0, "internal": 0 }, "buildTag": "v23.2.0-rc.2", "startedAt": "1705098699112441000", "localityAddress": [ ], "clusterName": "", "sqlAddress": { "networkField": "tcp", "addressField": "127.0.0.1:26259" }, "httpAddress": { "networkField": "tcp", "addressField": "127.0.0.1:8082" } }, ... ], "report": { "underReplicated": [ { "rangeDescriptor": { "rangeId": "74", "startKey": "84kSc2FuIGZyYW5jaXNjbwABEnd3d3d3d0gA/4AA/wD/AP8A/wD/AP8HAAE=", "endKey": "84kSc2FuIGZyYW5jaXNjbwABEoiIiIiIiEgA/4AA/wD/AP8A/wD/AP8IAAE=", "internalReplicas": [ { "nodeId": 3, "storeId": 3, "replicaId": 1, "type": 0 }, { "nodeId": 1, "storeId": 1, "replicaId": 6, "type": 0 }, { "nodeId": 2, "storeId": 2, "replicaId": 7, "type": 0 }, { "nodeId": 4, "storeId": 4, "replicaId": 4, "type": 5 }, { "nodeId": 8, "storeId": 8, "replicaId": 5, "type": 5 }, { "nodeId": 5, "storeId": 5, "replicaId": 8, "type": 5 }, { "nodeId": 9, "storeId": 9, "replicaId": 9, "type": 5 }, { "nodeId": 6, "storeId": 6, "replicaId": 10, "type": 5 } ], "nextReplicaId": 11, "generation": "43", "stickyBit": { "wallTime": "9223372036854775807", "logical": 2147483647, "synthetic": false } }, "config": { "rangeMinBytes": "134217728", "rangeMaxBytes": "536870912", "gcPolicy": { "ttlSeconds": 14400, "protectionPolicies": [ ], "ignoreStrictEnforcement": false }, "globalReads": false, "numReplicas": 9, "numVoters": 3, "constraints": [ { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "europe-west1" } ] }, { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] }, { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "us-west1" } ] } ], "voterConstraints": [ { "numReplicas": 0, "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] } ], "leasePreferences": [ { "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] } ], "rangefeedEnabled": false, "excludeDataFromBackup": false } }, ... ], "overReplicated": [ ], "violatingConstraints": [ ], "unavailable": [ ], "unavailableNodeIds": [ ] } } ``` ##### Replication status - ranges in critical localities The following example assumes you are running a newly started, local multi-region [`cockroach demo`](/docs/v26.4/cockroach-demo) cluster started using the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach demo --global --nodes 9 --insecure ``` Execute the following statements to set the [database regions](/docs/v26.4/multiregion-overview#database-regions) for the [`movr` database](/docs/v26.4/movr#the-movr-database): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE movr SET PRIMARY REGION "us-east1"; ALTER DATABASE movr ADD REGION "us-west1"; ALTER DATABASE movr ADD REGION "europe-west1"; ``` By default, this multi-region demo cluster will not have any [nodes](/docs/v26.4/architecture/overview#node) in a critical state. A node is *critical* if that node becoming unreachable would cause [replicas to become unavailable](/docs/v26.4/ui-cluster-overview-page#replication-status). The status endpoint describes which of your nodes (if any) are critical via the `criticalNodes` field in the response. To artificially put the nodes in this demo cluster in "critical" status, we can issue the following SQL statement, which uses [`ALTER DATABASE ... ALTER LOCALITY ... CONFIGURE ZONE`](/docs/v26.4/alter-database#alter-locality) to tell the cluster to store more copies of each range underlying the `movr` database than there are nodes in the cluster. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ALTER DATABASE movr ALTER LOCALITY REGIONAL IN "us-east1" CONFIGURE ZONE USING num_replicas = 128; ``` The critical nodes endpoint should now report that all of the cluster's nodes are critical by listing them in the `criticalNodes` field of the response. > [!TIP] > > Use the [`SHOW RANGES`](/docs/v26.4/show-ranges) statement to find out more information about the ranges in critical localities. > > In a real life critical localities scenario, you may need to [Troubleshoot your replication zones](/docs/v26.4/troubleshoot-replication-zones). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -X POST http://localhost:8080/_status/critical_nodes ``` ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "criticalNodes": [ { "nodeId": 3, "address": { "networkField": "tcp", "addressField": "127.0.0.1:26359" }, "attrs": { "attrs": [ ] }, "locality": { "tiers": [ { "key": "region", "value": "us-east1" }, { "key": "az", "value": "d" } ] }, "ServerVersion": { "majorVal": 23, "minorVal": 2, "patch": 0, "internal": 0 }, "buildTag": "v23.2.0-rc.2", "startedAt": "1705098699112441000", "localityAddress": [ ], "clusterName": "", "sqlAddress": { "networkField": "tcp", "addressField": "127.0.0.1:26259" }, "httpAddress": { "networkField": "tcp", "addressField": "127.0.0.1:8082" } }, ... ], "report": { "underReplicated": [ { "rangeDescriptor": { "rangeId": "100", "startKey": "8w==", "endKey": "84kSYm9zdG9uAAESIiIiIiIiQgD/gAD/AP8A/wD/AP8A/wIAAQ==", "internalReplicas": [ { "nodeId": 3, "storeId": 3, "replicaId": 1, "type": 0 }, { "nodeId": 5, "storeId": 5, "replicaId": 2, "type": 5 }, { "nodeId": 1, "storeId": 1, "replicaId": 3, "type": 0 }, { "nodeId": 2, "storeId": 2, "replicaId": 4, "type": 0 }, { "nodeId": 9, "storeId": 9, "replicaId": 5, "type": 5 }, { "nodeId": 4, "storeId": 4, "replicaId": 6, "type": 5 }, { "nodeId": 7, "storeId": 7, "replicaId": 7, "type": 5 }, { "nodeId": 6, "storeId": 6, "replicaId": 8, "type": 5 }, { "nodeId": 8, "storeId": 8, "replicaId": 9, "type": 5 } ], "nextReplicaId": 10, "generation": "38", "stickyBit": { "wallTime": "0", "logical": 0, "synthetic": false } }, "config": { "rangeMinBytes": "134217728", "rangeMaxBytes": "536870912", "gcPolicy": { "ttlSeconds": 14400, "protectionPolicies": [ ], "ignoreStrictEnforcement": false }, "globalReads": false, "numReplicas": 128, "numVoters": 3, "constraints": [ { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "europe-west1" } ] }, { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] }, { "numReplicas": 1, "constraints": [ { "type": 0, "key": "region", "value": "us-west1" } ] } ], "voterConstraints": [ { "numReplicas": 0, "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] } ], "leasePreferences": [ { "constraints": [ { "type": 0, "key": "region", "value": "us-east1" } ] } ], "rangefeedEnabled": false, "excludeDataFromBackup": false } }, ... ], "overReplicated": [ ], "violatingConstraints": [ ], "unavailable": [ ], "unavailableNodeIds": [ ] } } ``` ### Store status endpoint The store status endpoint at `/_status/stores` provides information about the [stores](/docs/v26.4/cockroach-start#store) attached to each [node](/docs/v26.4/architecture/overview#node) of your cluster. The response is a JSON object containing a `stores` array of objects. Each store object has the following fields: | Field | Description | | - | - | | `storeId` | The [store ID](/docs/v26.4/alter-range#find-the-cluster-store-ids) associated with this [store](/docs/v26.4/cockroach-start#store). | | `nodeId` | The [node ID](/docs/v26.4/cockroach-node#list-node-ids) associated with this [store](/docs/v26.4/cockroach-start#store). | | `encryptionStatus` | The [encryption status](/docs/v26.4/encryption#checking-encryption-status) of this [store](/docs/v26.4/cockroach-start#store). | | `totalFiles` | If the store is [encrypted](/docs/v26.4/encryption), the total number of encrypted files on the store. | | `totalBytes` | If the store is [encrypted](/docs/v26.4/encryption), the total number of encrypted bytes on the store. | | `activeKeyFiles` | If the store is [encrypted](/docs/v26.4/encryption),, the number of files using the [active data key](/docs/v26.4/encryption#changing-encryption-algorithm-or-keys). | | `activeKeyBytes` | If the store is [encrypted](/docs/v26.4/encryption),, the number of bytes using the [active data key](/docs/v26.4/encryption#changing-encryption-algorithm-or-keys). | | `dir` | The directory on disk where the [store](/docs/v26.4/cockroach-start#store) is located. | | `walFailoverPath` | If [WAL failover is enabled](/docs/v26.4/cockroach-start#enable-wal-failover), this field encodes the path to the secondary WAL directory used for failover in the event of high write latency to the primary WAL. | For example, to get the status of the stores of nodeID `1`, use the following: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl http://localhost:8080/_status/stores/1 ``` ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} { "stores": [ { "storeId": 1, "nodeId": 1, "encryptionStatus": null, "totalFiles": "0", "totalBytes": "0", "activeKeyFiles": "0", "activeKeyBytes": "0", "dir": "/tmp/node0", "walFailoverPath": "" } ] } ``` ## Alerting tools In addition to actively monitoring the overall health and performance of a cluster, it is also essential to configure alerting rules that promptly send notifications when CockroachDB experiences events that require investigation or intervention. Many of the [third-party monitoring integrations](/docs/v26.4/third-party-monitoring-tools), such as Datadog and Kibana, also support event-based alerting using metrics collected from a cluster's [Prometheus endpoint](/docs/v26.4/prometheus-endpoint). Refer to the documentation for an integration for more details. This section identifies the most important events that you might want to create alerting rules for, and provides pre-defined rules definitions for these events appropriate for use with Prometheus's [Alertmanager](https://prometheus.io/docs/alerting/latest/alertmanager/) service. ### Alertmanager If you have configured [Prometheus](/docs/v26.4/monitor-cockroachdb-with-prometheus) to monitor your CockroachDB instance, you can also configure alerting rule definitions to have Alertmanager detect [important events](#events-to-alert-on) and alert you when they occur. #### Prometheus alerting rules endpoint Every CockroachDB node exports an alerting rules template at `http:// 0 for: 10m0s annotations: summary: Instance has unavailable ranges - alert: TrippedReplicaCircuitBreakers expr: (sum by(instance, cluster) (kv_replica_circuit_breaker_num_tripped_replicas)) > 0 for: 10m0s annotations: summary: Instance has tripped per-Replica circuit breakers ... ``` #### Working with Alertmanager rules To add a rule from the `api/v2/rules/` rules endpoint, create or edit your `alerts.rules.yml` file and copy the rule definition for the event you want to alert on. For example, to add a rule to alert you when unavailable ranges are detected, copy the following from the rules endpoint into your `alerts.rules.yml` file: ``` - alert: UnavailableRanges expr: (sum by(instance, cluster) (ranges_unavailable)) > 0 for: 10m0s annotations: summary: Instance has unavailable ranges ``` If you already followed the steps from [Monitor CockroachDB with Prometheus](/docs/v26.4/monitor-cockroachdb-with-prometheus), you should already have a `alerts.rules.yml` file. If you are creating a new `alerts.rules.yml` file, be sure that it begins with the following three lines: ``` groups: - name: rules/alerts.rules rules: ``` Place your desired rule(s) underneath the `rules:` header. For example, the following shows an `alerts.rules.yml` file with the unavailable ranges rule defined: ``` groups: - name: rules/alerts.rules rules: - alert: UnavailableRanges expr: (sum by(instance, cluster) (ranges_unavailable)) > 0 for: 10m0s annotations: summary: Instance has unavailable ranges ``` Once you have created or edited your `alerts.rules.yml` file, reference it in your `prometheus.yml` configuration file with the following: ``` rule_files: - "rules/alerts.rules.yml" ``` If you already followed the steps from [Monitor CockroachDB with Prometheus](/docs/v26.4/monitor-cockroachdb-with-prometheus), this reference is already present in your `prometheus.yml` file. Start Prometheus and Alertmanager to begin watching for events to alert on. You can view imported rules on your Prometheus server's web interface at `http:// [!NOTE] > > Currently, not all events listed have corresponding alert rule definitions available from the `api/v2/rules/` endpoint. Many events not yet available in this manner are defined in the [pre-defined alerting rules](https://docs.cockroachlabs.com/files/cockroach/monitoring/rules/alerts.rules.yaml). For more details, see [Monitor CockroachDB with Prometheus](/docs/v26.4/monitor-cockroachdb-with-prometheus). #### Node is down * **Rule:** Send an alert when a node has been down for 15 minutes or more. * **How to detect:** If a node is down, its Prometheus endpoint will return a `Connection refused` error. Otherwise, the `liveness_livenodes` metric will be the total number of live nodes in the cluster. * **Rule definition:** Use the `InstanceDead` alert from our [pre-defined alerting rules](https://docs.cockroachlabs.com/files/cockroach/monitoring/rules/alerts.rules.yaml). #### Node is restarting too frequently * **Rule:** Send an alert if a node has restarted more than once in the last 10 minutes. * **How to detect:** Calculate this using the number of times the `sys_uptime` metric in the node's Prometheus endpoint output was reset back to zero. The `sys_uptime` metric gives you the length of time, in seconds, that the `cockroach` process has been running. * **Rule definition:** Use the `InstanceFlapping` alert from our [pre-defined alerting rules](https://docs.cockroachlabs.com/files/cockroach/monitoring/rules/alerts.rules.yaml). #### Node is running low on disk space * **Rule:** Send an alert when a node has less than 15% of free space remaining. * **How to detect:** Divide the `capacity` metric by the `capacity_available` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `StoreDiskLow` alert from our [pre-defined alerting rules](https://docs.cockroachlabs.com/files/cockroach/monitoring/rules/alerts.rules.yaml). For instructions on how to free up disk space as quickly as possible after dropping a table, see [How can I free up disk space that was used by a dropped table?](/docs/v26.4/operational-faqs#how-can-i-free-up-disk-space-when-dropping-a-table) #### Node is not executing SQL * **Rule:** Send an alert when a node is not executing SQL despite having connections. * **How to detect:** The `sql_conns` metric in the node's Prometheus endpoint output will be greater than `0` while the `sql_query_count` metric will be `0`. You can also break this down by statement type using `sql_select_count`, `sql_insert_count`, `sql_update_count`, and `sql_delete_count`. #### CA certificate expires soon * **Rule:** Send an alert when the CA certificate on a node will expire in less than a year. * **How to detect:** Calculate this using the `security_certificate_expiration_ca` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `CACertificateExpiresSoon` alert from our [pre-defined alerting rules](https://docs.cockroachlabs.com/files/cockroach/monitoring/rules/alerts.rules.yaml). #### Node certificate expires soon * **Rule:** Send an alert when a node's certificate will expire in less than a year. * **How to detect:** Calculate this using the `security_certificate_expiration_node` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `NodeCertificateExpiresSoon` alert from our [pre-defined alerting rules](https://docs.cockroachlabs.com/files/cockroach/monitoring/rules/alerts.rules.yaml). #### Changefeed is experiencing high latency * **Rule:** Send an alert when the latency of any changefeed running on any node is higher than the set threshold, which depends on the [`gc.ttlseconds`](/docs/v26.4/configure-replication-zones#replication-zone-variables) variable set in the cluster. * **How to detect:** Calculate this using a threshold, where the threshold is less than the value of the [`gc.ttlseconds`](/docs/v26.4/configure-replication-zones#replication-zone-variables) variable. For example, `changefeed.max_behind_nanos > [some threshold]`. #### Unavailable ranges * **Rule:** Send an alert when the number of ranges with fewer live replicas than needed for quorum is non-zero for too long. * **How to detect:** Calculate this using the `ranges_unavailable` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `UnavailableRanges` alerting rule from your cluster's [`api/v2/rules/` metrics endpoint](#alertmanager). #### Tripped replica circuit breakers * **Rule:** Send an alert when a replica stops serving traffic due to other replicas being offline for too long. * **How to detect:** Calculate this using the `kv_replica_circuit_breaker_num_tripped_replicas` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `TrippedReplicaCircuitBreakers` alerting rule from your cluster's [`api/v2/rules/` metrics endpoint](#alertmanager). #### Under-replicated ranges * **Rule:** Send an alert when the number of ranges with replication below the [replication factor](/docs/v26.4/configure-replication-zones#num_replicas) is non-zero for too long. * **How to detect:** Calculate this using the `ranges_underreplicated` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `UnderreplicatedRanges` alerting rule from your cluster's [`api/v2/rules/` metrics endpoint](#alertmanager). #### Requests stuck in Raft * **Rule:** Send an alert when requests are taking a very long time in replication. This can be a symptom of a [leader-leaseholder split](/docs/v26.4/architecture/replication-layer). * **How to detect:** Calculate this using the `requests_slow_raft` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `RequestsStuckInRaft` alerting rule from your cluster's [`api/v2/rules/` metrics endpoint](#alertmanager). #### High open file descriptor count * **Rule:** Send an alert when a cluster is getting close to the [open file descriptor limit](/docs/v26.4/recommended-production-settings#file-descriptors-limit). * **How to detect:** Calculate this using the `sys_fd_softlimit` metric in the node's Prometheus endpoint output. * **Rule definition:** Use the `HighOpenFDCount` alerting rule from your cluster's [`api/v2/rules/` metrics endpoint](#alertmanager). ## See also * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) * [Third-Party Monitoring Integrations](/docs/v26.4/third-party-monitoring-tools) * [Metrics](/docs/v26.4/metrics) * [Troubleshoot Replication Zones](/docs/v26.4/troubleshoot-replication-zones) # MovR Source: https://docs.cockroachlabs.com/docs/stable/movr MovR is a fictional vehicle-sharing company created to demonstrate CockroachDB's features. ## Overview The MovR example consists of the following: * The `movr` dataset, which contains rows of data that populate tables in the `movr` database. The `movr` dataset is built into [`cockroach demo`](/docs/v26.4/cockroach-demo) and [`cockroach workload`](/docs/v26.4/cockroach-workload). * The MovR application, a fully-functional vehicle-sharing application, written in Python. All of MovR application source code is open-source, and available on the [movr](https://github.com/cockroachdb/movr) GitHub repository. ## The `movr` database The six tables in the `movr` database store user, vehicle, and ride data for MovR: | Table | Description | | - | - | | `users` | People registered for the service. | | `vehicles` | The pool of vehicles available for the service. | | `rides` | When and where users have rented a vehicle. | | `promo_codes` | Promotional codes for users. | | `user_promo_codes` | Promotional codes in use by users. | | `vehicle_location_histories` | Vehicle location history. | ![Geo-partitioning schema](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/movr-schema.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=28dd86accbcfbaf387922fdf344ff73a) ## Generating schemas and data for MovR You can use the `cockroach demo` and `cockroach workload` commands to load the `movr` database and dataset into a CockroachDB cluster. [`cockroach demo`](/docs/v26.4/cockroach-demo) opens a SQL shell to a temporary, in-memory cluster. To open a SQL shell to a demo cluster with the `movr` database preloaded and set as the [current database](/docs/v26.4/sql-name-resolution#current-database), use the following command: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach demo movr ``` [`cockroach workload`](/docs/v26.4/cockroach-workload) loads sample datasets and workloads into running clusters. To load the `movr` database and some sample data into a running cluster, do the following: > [tab] Secure > > 1. Start a [secure](/docs/v26.4/secure-a-cluster) local cluster. > > 2. Use `cockroach workload` to load the `movr` dataset: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach workload init movr 'postgresql://root@localhost:26257?sslcert=certs%2Fclient.root.crt&sslkey=certs%2Fclient.root.key&sslmode=verify-full&sslrootcert=certs%2Fca.crt' > ``` > > 3. Use [`cockroach sql`](/docs/v26.4/cockroach-sql) to open an interactive SQL shell and set `movr` as the [current database](/docs/v26.4/sql-name-resolution#current-database): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --certs-dir=certs --host=localhost:26257 > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > USE movr; > ``` > [tab] Insecure > > 1. Start an [insecure](/docs/v26.4/start-a-local-cluster) local cluster. > > 2. Use `cockroach workload` to load the `movr` dataset: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach workload init movr 'postgresql://root@localhost:26257?sslmode=disable' > ``` > > 3. Use [`cockroach sql`](/docs/v26.4/cockroach-sql) to open an interactive SQL shell and set `movr` as the [current database](/docs/v26.4/sql-name-resolution#current-database): > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > $ cockroach sql --insecure --host=localhost:26257 > ``` > > ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > > USE movr; > ``` ## How the MovR application works The workflow for MovR is as follows: 1. A user loads the app and sees the 25 closest vehicles. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT id, city, status FROM vehicles WHERE city='amsterdam' limit 25; ``` 2. The user signs up for the service. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO users (id, name, address, city, credit_card) VALUES ('66666666-6666-4400-8000-00000000000f', 'Mariah Lam', '88194 Angela Gardens Suite 60', 'amsterdam', '123245696'); ``` 3. In some cases, the user adds their own vehicle to share. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO vehicles (id, city, type, owner_id,creation_time,status, current_location, ext) VALUES ('ffffffff-ffff-4400-8000-00000000000f', 'amsterdam', 'skateboard', '66666666-6666-4400-8000-00000000000f', current_timestamp(), 'available', '88194 Angela Gardens Suite 60', '{"color": "blue"}'); ``` 4. More often, the user reserves a vehicle and starts a ride, applying a promo code, if available and valid. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT code FROM user_promo_codes WHERE user_id ='66666666-6666-4400-8000-00000000000f'; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE vehicles SET status = 'in_use' WHERE id='bbbbbbbb-bbbb-4800-8000-00000000000b'; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO rides (id, city, vehicle_city, rider_id, vehicle_id, start_address,end_address, start_time, end_time, revenue) VALUES ('cd032f56-cf1a-4800-8000-00000000066f', 'amsterdam', 'amsterdam', '66666666-6666-4400-8000-00000000000f', 'bbbbbbbb-bbbb-4800-8000-00000000000b', '70458 Mary Crest', '', TIMESTAMP '2020-10-01 10:00:00.123456', NULL, 0.0); ``` 5. During the ride, MovR tracks the location of the vehicle. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO vehicle_location_histories (city, ride_id, timestamp, lat, long) VALUES ('amsterdam', 'cd032f56-cf1a-4800-8000-00000000066f', current_timestamp(), -101, 60); ``` 6. The user ends the ride and releases the vehicle. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE vehicles SET status = 'available' WHERE id='bbbbbbbb-bbbb-4800-8000-00000000000b'; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > UPDATE rides SET end_address ='33862 Charles Junctions Apt. 49', end_time=TIMESTAMP '2020-10-01 10:30:00.123456', revenue=88.6 WHERE id='cd032f56-cf1a-4800-8000-00000000066f'; ``` ## See also * [Features in Preview](/docs/releases/cockroachdb-feature-availability) # Multi-Active Availability Source: https://docs.cockroachlabs.com/docs/stable/multi-active-availability CockroachDB's availability model is described as "Multi-Active Availability." In essence, multi-active availability provides benefits similar to traditional notions of high availability, but also lets you read and write from every node in your cluster without generating any conflicts. ## What is high availability? High availability lets an application continue running even if a system hosting one of its services fails. This is achieved by scaling the application's services horizontally, i.e., replicating the service across many machines or systems. If any one of them fails, the others can simply step in and perform the same service. Before diving into the details of CockroachDB's multi-active availability, we'll review the two most common high availability designs: [Active-Passive](#active-passive) and [Active-Active](#active-active) systems. ### Active-passive In active-passive systems, all traffic is routed to a single, "active" replica. Changes to the replica's state are then copied to a backup "passive" replica, in an attempt to always mirror the active replica as closely as possible. However, this design has downsides: * If you use asynchronous replication, you cannot guarantee that any data is ever successfully replicated to passive followers––meaning you can easily lose data. Depending on your industry, this could have pretty dire consequences. * If you use synchronous replication and any passive replicas fail, you have to either sacrifice availability for the entire application or risk inconsistencies. ### Active-active In active-active systems, multiple replicas run identical services, and traffic is routed to all of them. If any replica fails, the others simply handle the traffic that would've been routed to it. For databases, though, active-active replication is incredibly difficult to instrument for most workloads. For example, if you let multiple replicas handle writes for the same keys, how do you keep them consistent? #### Example: conflicts with active-active replication For this example, we have 2 replicas (**A**, **B**) in an active-active high availability cluster. 1. **A** receives a write for key `xyz` of `'123'`, and then immediately fails. 2. **B** receives a read of key `xyz`, and returns a `NULL` because it cannot find the key. 3. **B** then receives a write for key `xyz` of `'456'`. 4. **A** is restarted and attempts to rejoin **B**––but what do you do about key `xyz`? There's an inconsistency in the system without a clear way to resolve it. > [!NOTE] > > In this example, the cluster remained active the entire time. But in terms of the CAP theorem, this is an AP system; it favored being available instead of consistent when partitions occur. ## What is multi-active availability? Multi-active availability is CockroachDB's version of high availability (keeping your application online in the face of partial failures), which we've designed to avoid the downsides of both active-passive and traditional active-active systems. Like active-active designs, all replicas can handle traffic, including both reads and writes. However, CockroachDB improves upon that design by also ensuring that data remains consistent across them, which we achieve by using "consensus replication." In this design, replication requests are sent to at least 3 replicas, and are only considered committed when a majority of replicas acknowledge that they've received it. This means that you can still have failures without compromising availability. To prevent conflicts and guarantee your data's consistency, clusters that lose a majority of replicas stop responding because they've lost the ability to reach a consensus on the state of your data. When a majority of replicas are restarted, your database resumes operation. ### Consistency example For this example, we have 3 CockroachDB nodes (**A**, **B**, **C**) in a multi-active availability cluster. 1. **A** receives a write on `xyz` of `'123'`. It communicates this write to nodes **B** and **C**, who confirm that they've received the write, as well. Once **A** receives the first confirmation, the change is committed. 2. **A** fails. 3. **B** receives a read of key `xyz`, and returns the result `'123'`. 4. **C** then receives an update for key `xyz` to the values `'456'`. It communicates this write to node **B**, who confirms that its received the write, as well. After receiving the confirmation, the change is committed. 5. **A** is restarted and rejoins the cluster. It receives an update that the key `xyz` had its value changed to `'456'`. In this example, if nodes **BC** failed at any time, the cluster would have stopped responding. In terms of the CAP theorem, this is a CP system; it favored being consistent instead of available when partitions occur. ## What's next? To get a greater understanding of how CockroachDB is a survivable system that enforces strong consistency, check out our [architecture documentation](/docs/v26.4/architecture/overview). To see Multi-Active Availability in action, see this [availability demo](/docs/v26.4/demo-cockroachdb-resilience). # SASL OAUTHBEARER (OAuth 2.0) Authentication for SQL Clients Source: https://docs.cockroachlabs.com/docs/stable/oauth-authentication CockroachDB supports SASL OAUTHBEARER ([RFC 7628](https://www.rfc-editor.org/rfc/rfc7628)) authentication for SQL client connections. With OAUTHBEARER, a SQL client presents an OAuth 2.0 bearer token issued by your identity provider (IdP), such as Okta, Keycloak, Microsoft Entra ID, or Google, and CockroachDB validates the token and maps it to a SQL user. The token must be a JWT. CockroachDB cannot validate opaque access tokens. For example, Google issues opaque access tokens, so the device flow does not work with Google. Only a Google ID token presented by a driver can be validated. The protocol matches the OAuth support in PostgreSQL 18, so `psql` 18, `libpq` 18, and PostgreSQL-compatible drivers that implement OAUTHBEARER can authenticate to CockroachDB without any CockroachDB-specific client logic. This page describes how to configure a cluster for OAUTHBEARER authentication, how to connect with `cockroach sql`, `psql`, and other clients, and how to manage users that the cluster provisions automatically. ## Overview CockroachDB offers two ways to authenticate SQL clients with tokens from an external IdP: * **SASL OAUTHBEARER** (this page): the client sends a bearer token in a standard SASL exchange. The client can obtain the token itself, or `cockroach sql` and `psql` 18 can run an interactive [OAuth 2.0 device authorization flow](https://www.rfc-editor.org/rfc/rfc8628) in a browser and connect with the resulting token. Use this method when your clients support OAUTHBEARER natively. * **[Cluster single sign-on (SSO) using JWTs](/docs/v26.4/sso-sql)**: the client sends a JSON Web Token (JWT) in place of a password. Use this method with clients that do not implement OAUTHBEARER but accept a long password. Both methods validate the same token properties (issuer, signing key, expiry, and audience), and both support [automatic user provisioning](#step-4-configure-user-creation) and [group-based role synchronization](#step-5-enable-group-based-authorization-optional). The two methods are configured with separate cluster settings and separate [host-based authentication (HBA)](/docs/v26.4/security-reference/authentication#authentication-configuration) methods, so you can enable either or both. The methods differ in two ways: OAUTHBEARER requires the identity claim to hold exactly one value (refer to [Step 1](#step-1-configure-cluster-settings)), and OAUTHBEARER does not cache JWKS keys between logins. When OAUTHBEARER authentication is enabled, a node handles each login as follows: 1. The client connects over TLS and requests a SQL user. The server advertises the `OAUTHBEARER` SASL mechanism. 2. The client sends a bearer token. If the client has no token yet, it sends an empty token, and the server responds with the information the client needs to obtain one (refer to [Error response](#error-response)). 3. The server reads the token principal from the configured claim, before the token is verified, and, if an identity map is configured, maps it to a SQL username. The result must match the SQL user that the client requested. 4. If the user does not exist and [automatic user provisioning](#option-1-automatic-user-provisioning-recommended) is enabled, the server verifies the token's signature against the issuer's JSON Web Key Set (JWKS) and checks its issuer, then creates the user. 5. The server fully validates the token: signature, issuer, expiry, and audience. 6. If [group-based authorization](#step-5-enable-group-based-authorization-optional) is enabled, the server synchronizes the user's role memberships from the token's group claim. Authentication events are recorded in the [`SESSIONS`](/docs/v26.4/logging#sessions) logging channel. > [!NOTE] > > OAUTHBEARER authentication cannot be used for the `root` user or other [reserved identities](/docs/v26.4/security-reference/authorization#reserved-identities). Credentials for `root` must be managed separately using password or certificate authentication to ensure continuous administrative access regardless of IdP availability. ## Prerequisites * An identity provider that issues JWT-format OAuth 2.0 access tokens and publishes its signing keys as a JWKS, typically through an OpenID Connect discovery document at `https://{issuer URL}/.well-known/openid-configuration`. * A cluster that is fully upgraded to v26.4. The `oauth` HBA method is gated on the v26.4 cluster version. If you configure it before the upgrade is finalized, the `SET CLUSTER SETTING` statement fails with an `ObjectNotInPrerequisiteState` error. * A secure cluster. The `oauth` HBA method is accepted only on TLS connections. * The ability to update cluster settings. Refer to [`SET CLUSTER SETTING`: Required permissions](/docs/v26.4/set-cluster-setting#required-privileges). * SQL users that correspond to your external identities, unless you enable [automatic user provisioning](#option-1-automatic-user-provisioning-recommended). To create users, you must have access to the [`admin` role](/docs/v26.4/security-reference/authorization#admin-role). * For the interactive device flow with `cockroach sql` or `psql`, an OAuth client registered with your IdP as a **public** client (no client secret) with the device authorization grant enabled, and an issuer that is reachable over HTTPS. Before you begin, enable authentication logging to help confirm your configuration or troubleshoot issues. Refer to [Troubleshooting](#troubleshooting). ## Configuration ### Step 1: Configure cluster settings OAUTHBEARER authentication is controlled by the [cluster settings](/docs/v26.4/cluster-settings) in the following table. Each setting applies only to OAUTHBEARER logins; the [`server.jwt_authentication.*` settings](/docs/v26.4/sso-sql#cluster-settings) for cluster SSO using JWTs are separate. | Cluster Setting | Description | Default | | - | - | - | | [`server.oauthbearer_authentication.enabled`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-enabled) | Enables or disables SASL OAUTHBEARER login for the SQL interface. Must be set to `true`. | `false` | | [`server.oauthbearer_authentication.issuers`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-issuers) | The accepted token issuers. Can be any of the following:
  • A string representing a single issuer URL
  • A string that contains a JSON array of issuer URLs
  • A string that contains a JSON object mapping issuer URLs to JWKS URIs
The format is detected automatically. A token whose `iss` claim is not in this list is rejected. | (empty) | | [`server.oauthbearer_authentication.issuers.custom_ca`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-issuers-custom-ca) | A PEM-encoded custom root CA certificate used to verify the issuer's TLS certificate when fetching a JWKS or querying the userinfo endpoint. Set this when your IdP uses a private CA. | (empty) | | [`server.oauthbearer_authentication.audience`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-audience) | The accepted audience values, as a single string or a JSON array of strings. A token is accepted only if its `aud` claim contains one of these values. Tokens are rejected when this setting is empty, so you must set it to the audience your IdP places in tokens for CockroachDB, typically the OAuth client ID. | (empty) | | [`server.oauthbearer_authentication.jwks`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-jwks) | A static JSON Web Key Set containing the public signing keys of your issuers. Ignored when `server.oauthbearer_authentication.jwks_auto_fetch.enabled` is `true`. | `{"keys":[]}` | | [`server.oauthbearer_authentication.jwks_auto_fetch.enabled`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-jwks-auto-fetch-enabled) | If `true`, each node fetches signing keys from the issuer's discovery document (or from the JWKS URI given in `server.oauthbearer_authentication.issuers`) on every login, so you do not need to maintain `server.oauthbearer_authentication.jwks` as the IdP rotates keys. | `false` | | [`server.oauthbearer_authentication.claim`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-claim) | The token claim whose value identifies the user. Can be a simple claim name such as `email`, or an [RFC 6901 JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) such as `/kubernetes.io/serviceaccount/uid` for a nested claim. When empty, the `sub` claim is used. The claim must hold exactly one value; a multi-valued claim is rejected. This differs from the JWT method, which accepts whichever value matches the requested user. | (empty) | | [`server.oauthbearer_authentication.scope`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-scope) | The OAuth scope advertised to clients in the [error response](#error-response) when a token is missing or rejected. Discovery-driven clients such as `psql` request this scope from the IdP. This setting is not used to validate tokens. | (empty) | | [`server.oauthbearer_authentication.client.timeout`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-client-timeout) | The timeout for HTTP calls the node makes during OAUTHBEARER authentication, such as fetching a JWKS or querying the userinfo endpoint. | `15s` | | [`server.oauthbearer_authentication.authorization.enabled`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-authorization-enabled) | Enables [group-based role synchronization](#step-5-enable-group-based-authorization-optional) from the token's group claim. | `false` | | [`server.oauthbearer_authentication.group_claim`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-group-claim) | The token claim that contains the user's groups, used for role synchronization. | `groups` | | [`server.oauthbearer_authentication.userinfo_group_key`](/docs/v26.4/cluster-settings#setting-server-oauthbearer-authentication-userinfo-group-key) | The JSON key to read from the issuer's userinfo endpoint when the group claim is absent from the token. | `groups` | | [`security.provisioning.oauth.enabled`](/docs/v26.4/cluster-settings#setting-security-provisioning-oauth-enabled) | Enables [automatic user provisioning](#option-1-automatic-user-provisioning-recommended) on first OAUTHBEARER login. | `false` | A minimal configuration enables the method, trusts one issuer, fetches that issuer's signing keys automatically, restricts the audience, and names the claim that holds the username: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.oauthbearer_authentication.enabled = true; SET CLUSTER SETTING server.oauthbearer_authentication.issuers = 'https://auth.example.com'; SET CLUSTER SETTING server.oauthbearer_authentication.jwks_auto_fetch.enabled = true; SET CLUSTER SETTING server.oauthbearer_authentication.audience = 'cockroachdb-sql'; SET CLUSTER SETTING server.oauthbearer_authentication.claim = 'email'; ``` To accept more than one issuer, set `server.oauthbearer_authentication.issuers` to a JSON array, or to a JSON object when an issuer's JWKS is not discoverable from its `.well-known/openid-configuration` endpoint: | Type | Example | | - | - | | Single issuer URL | `'https://auth.example.com'` | | Array of issuer URLs | `'["https://auth.example.com", "https://accounts.google.com"]'` | | Map of issuer URLs | `'{ "issuer_jwks_map": { "https://auth.example.com": "https://auth.example.com/oauth2/v1/keys", "https://accounts.google.com": "https://www.googleapis.com/oauth2/v3/certs" } }'` | > [!NOTE] > > Discovery-driven clients such as `psql` 18 rely on the server to advertise the issuer's OpenID configuration endpoint, and the server does so only when exactly one issuer is configured. If you configure several issuers, clients must be told the issuer explicitly (for example, with `--oauth-issuer` in `cockroach sql`), or must obtain a token on their own. If you prefer static signing keys, leave `server.oauthbearer_authentication.jwks_auto_fetch.enabled` at `false` and set `server.oauthbearer_authentication.jwks` to the JWKS published by your issuer. IdPs rotate their signing keys periodically, so you must update the static key set before the previous keys expire, or OAUTHBEARER logins will fail. Automatic fetching avoids this maintenance. Because the identity map and the HBA configuration can contain information you may not want all users to see, consider enabling redaction of those settings. Refer to [Sensitive settings](/docs/v26.4/cluster-settings#sensitive-settings). ### Step 2: Configure host-based authentication (HBA) To enable OAUTHBEARER for a set of users, add a rule with the `oauth` method to the [host-based authentication (HBA)](/docs/v26.4/security-reference/authentication#authentication-configuration) configuration in the cluster setting `server.host_based_authentication.configuration`. The simplest rule allows every user from every address to authenticate with a bearer token: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.host_based_authentication.configuration = 'host all all all oauth'; ``` The `oauth` method accepts two options, each of which may appear at most once on a rule: * `map=`: apply the named [identity map](#step-3-map-identities-optional) from `server.identity_map.configuration` to translate the token principal into a SQL username. Without `map=`, the value of the configured claim is used directly as the SQL username, so it must equal the username the client requests. * `issuer=`: accept only tokens issued by this issuer on this rule. The URL must be one of the issuers configured in `server.oauthbearer_authentication.issuers`. Without `issuer=`, a token from any configured issuer is accepted. Use this option to pair different issuers with different identity maps or user sets. For example, the following configuration maps principals from `https://auth.example.com` through the `crdb` identity map, and falls back to certificate or password authentication for anyone else: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.host_based_authentication.configuration = ' host all all all oauth map=crdb issuer=https://auth.example.com host all all all cert-password'; ``` Keep the following in mind: * The `oauth` method is accepted only on TLS connections. A client that matches an `oauth` rule over a non-TLS connection is rejected with `method "oauth" required for this user, but unusable over this connection type`. * Any option other than `map` and `issuer` is a configuration error, and the `SET CLUSTER SETTING` statement fails. * Setting an `oauth` rule before every node is running v26.4 and the upgrade is finalized fails with an `ObjectNotInPrerequisiteState` error. * `root` and other [reserved identities](/docs/v26.4/security-reference/authorization#reserved-identities) cannot log in with OAUTHBEARER, whether or not an identity map is used. The mandatory `root` rule continues to allow `root` to authenticate with a certificate or password. ### Step 3: Map identities (optional) If the usernames in your tokens do not match your SQL usernames exactly, configure an identity map in the cluster setting `server.identity_map.configuration` and reference it from the HBA rule with `map=`. The format follows PostgreSQL's [`pg_ident.conf`](https://www.postgresql.org/docs/current/auth-username-maps.html): each line is a space-separated triple: ` ` * `` is the name you pass to `map=` in the HBA rule. One configuration can hold several maps. * `` is matched against the value of the claim named by `server.oauthbearer_authentication.claim`. A value that starts with `/` is interpreted as a case-insensitive regular expression; anchor it with `^` and `$` to avoid partial matches. The expression may contain one capturing group. * `` is the SQL user the principal may log in as. It can include `\1` to substitute the capturing group. > [!NOTE] > > This differs from the identity map used by [cluster SSO using JWTs](/docs/v26.4/sso-sql#identity-map-configuration), where the first field is the issuer URL rather than a map name. For OAUTHBEARER, pin a rule to an issuer with the `issuer=` HBA option instead. For example, the following map lets any `@example.com` email address log in as the SQL user named by the part before the `@`, and lets the fixed subject `1232316645658094244789` log in as `roach`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.identity_map.configuration = ' crdb /^(.*)@example\.com$ \1 crdb 1232316645658094244789 roach'; ``` With this map and the rule `host all all all oauth map=crdb`, a token whose `email` claim is `alice@example.com` can log in as `alice`. The client still requests the SQL user to connect as (for example, `--user=alice`); the login fails if the mapped principal does not resolve to that user. ### Step 4: Configure user creation CockroachDB supports two approaches for the creation of users who authenticate with OAUTHBEARER: #### Option 1: Automatic user provisioning (recommended) With automatic user provisioning, CockroachDB creates a SQL user during the user's first successful OAUTHBEARER authentication. This eliminates the need to pre-create accounts for every identity in your IdP. When enabled: * Before the user is created, the token's signature is verified and its issuer is checked, so only identities from your configured issuers can be provisioned. Expiry and audience are checked after provisioning, as part of full token validation. * The new user receives a `PROVISIONSRC` role option set to `oauth:`, for example `oauth:https://auth.example.com`. * The `estimated_last_login_time` column of [`SHOW USERS`](/docs/v26.4/show-users) is tracked for auditing. * Auto-provisioned users cannot change their own passwords; their credentials are managed by the IdP. The username is the mapped token principal and must meet the CockroachDB [requirements for usernames](/docs/v26.4/create-user#user-names). > [!NOTE] > > Before you enable automatic user provisioning, Cockroach Labs recommends that you enable [group-based authorization](#step-5-enable-group-based-authorization-optional) and create the matching roles. This ensures that new users are members of the intended roles, with the privileges they confer, on their first login. Auto-provisioned users receive roles only for groups that already exist as CockroachDB roles. **To enable automatic user provisioning:** ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING security.provisioning.oauth.enabled = true; ``` To view and manage auto-provisioned users, refer to [Manage auto-provisioned users](#manage-auto-provisioned-users). #### Option 2: Manual or scripted user creation Alternatively, create users before they authenticate. The username must match the token principal after the identity map is applied. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE alice LOGIN; GRANT developers TO alice; ``` To create users in bulk, produce a `.sql` file with one [`CREATE ROLE`](/docs/v26.4/create-role) statement per user and run it with [`cockroach sql --file`](/docs/v26.4/cockroach-sql#execute-sql-statements-from-a-file). ### Step 5: Enable group-based authorization (optional) CockroachDB can synchronize a user's role memberships from the groups in their token on every OAUTHBEARER login, in the same way that [JWT authorization](/docs/v26.4/jwt-authorization) does for cluster SSO using JWTs. 1. Create CockroachDB roles whose names match your IdP group names, and grant privileges to those roles. Group names are normalized with case folding and Unicode normalization (NFC) before matching, so they typically match lowercase role names. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE ROLE developers; GRANT ALL ON DATABASE app TO developers; CREATE ROLE analysts; GRANT SELECT ON DATABASE analytics TO analysts; ``` 2. Enable authorization and, if your IdP uses a claim other than `groups`, name the claim: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.oauthbearer_authentication.authorization.enabled = true; SET CLUSTER SETTING server.oauthbearer_authentication.group_claim = 'groups'; SET CLUSTER SETTING server.oauthbearer_authentication.userinfo_group_key = 'groups'; ``` On each login: * The groups are read from the `group_claim` claim. If that claim is absent or malformed, the node queries the issuer's userinfo endpoint with the access token and reads the `userinfo_group_key` key from the response. If the issuer's discovery document has no `userinfo_endpoint`, the login fails with `No userinfo endpoint`. If the userinfo lookup fails, the login is rejected. If the userinfo response does not contain the `userinfo_group_key` key, all of the user's direct role memberships are revoked and the login is rejected. * The claim is expected to be a JSON array of strings, for example `["developers", "analysts"]`. If it is a single string, it is split on commas only, so `"developers,analysts"` yields two groups, while a name containing spaces, such as `"data platform"`, is one group. Identity providers that convey multiple groups should return a JSON array. * Each group that matches an existing role is granted to the user. Groups that do not match a role are silently skipped. * Roles that the user holds [directly](/docs/v26.4/security-reference/authorization#direct-member) but that no longer match a group are revoked. Roles held only [indirectly](/docs/v26.4/security-reference/authorization#indirect-member) through another role are not revoked individually. * If the group list exists but is empty, all of the user's direct role memberships are revoked and the login is rejected with `OAUTHBEARER authorization: empty group list`. * Any role can be synchronized, including privileged roles such as `admin`. An IdP group named `admin` grants the `admin` role on login, and removing the user from that group revokes it. Control membership in such groups carefully in your IdP. For IdP-specific guidance on exposing groups in tokens for Okta, Keycloak, and Microsoft Entra ID, refer to [JWT Authorization](/docs/v26.4/jwt-authorization#step-2-configure-idp-specific-settings); the same claim configuration applies to OAUTHBEARER tokens. ## Connect to the cluster Clients can authenticate with OAUTHBEARER in three ways. ### Connect with `cockroach sql` using the device flow [`cockroach sql`](/docs/v26.4/cockroach-sql) can obtain a token for you by running the [OAuth 2.0 device authorization grant](https://www.rfc-editor.org/rfc/rfc8628) against your IdP. Pass the issuer URL and the public OAuth client ID, and optionally the scopes to request: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql \ --url "postgresql://alice@db.example.com:26257/defaultdb?sslmode=verify-full" \ --certs-dir=certs \ --oauth-issuer=https://auth.example.com \ --oauth-client-id= \ --oauth-scope="openid email" ``` The shell fetches the issuer's discovery document, requests a device code, and prints a verification URL and a one-time code (opening a browser where one is available). After you sign in with your IdP, the shell receives the token and completes the SASL OAUTHBEARER exchange. No token is written to disk. | Flag | Environment variable | Description | | - | - | - | | `--oauth-issuer` | `COCKROACH_OAUTH_ISSUER` | The OAuth/OIDC issuer URL. Its discovery document must advertise a device authorization endpoint. | | `--oauth-client-id` | `COCKROACH_OAUTH_CLIENT_ID` | The public OAuth client identifier registered with the IdP for the device flow. | | `--oauth-scope` | `COCKROACH_OAUTH_SCOPE` | Optional space-separated scopes to request. Some identity providers, such as Okta, require a scope. | Keep the following in mind: * `--oauth-issuer` and `--oauth-client-id` must be specified together. * The connection must use `sslmode=verify-full`. The shell refuses to send a bearer token over a plaintext connection, or over a TLS connection that does not verify the server's identity, with an error such as `refusing to send an OAuth token over a plaintext connection` and the hint `use sslmode=verify-full`. * The issuer and the endpoints in its discovery document must use `https`. For local development against an IdP without TLS, set the environment variable `COCKROACH_OAUTH_ALLOW_INSECURE_ISSUER=true`. This relaxes only the check on the issuer's endpoints, with a warning; the `sslmode=verify-full` requirement for the connection to CockroachDB still applies. Do not use this setting in production. * The SQL user in the connection URL must be the user that the token principal maps to. ### Connect with `psql` 18 or `libpq` PostgreSQL 18 `libpq`, and therefore `psql` 18 and clients built on `libpq`, implement OAUTHBEARER with a built-in device flow. Supply the issuer and client ID as connection parameters: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} psql "host=db.example.com port=26257 dbname=defaultdb user=alice sslmode=verify-full sslrootcert=certs/ca.crt oauth_issuer=https://auth.example.com oauth_client_id= require_auth=oauth" ``` `libpq` verifies that `oauth_issuer` matches the OpenID configuration endpoint that the server advertises in its [error response](#error-response). CockroachDB advertises that endpoint only when exactly one issuer is configured in `server.oauthbearer_authentication.issuers`, so the `libpq` device flow requires a single-issuer configuration. If `server.oauthbearer_authentication.scope` is set, `libpq` requests that scope; otherwise, set `oauth_scope` in the connection string. For the full list of OAuth connection parameters, including `oauth_client_secret` and `oauth_scope`, refer to the [PostgreSQL `libpq` documentation](https://www.postgresql.org/docs/18/libpq-connect.html#LIBPQ-PARAMKEYWORDS). ### Connect with a driver and a pre-obtained token Drivers that implement SASL OAUTHBEARER, such as [`pgx`](https://github.com/jackc/pgx) for Go, let your application supply a bearer token through a token-provider callback in the connection configuration. Your application obtains the token from the IdP by whatever OAuth flow suits it (for example, the client credentials grant for a service account) and the driver presents it when the server advertises `OAUTHBEARER`. The SQL user in the connection configuration must be the user that the token principal maps to through `server.oauthbearer_authentication.claim` and the identity map. Clients that do not implement OAUTHBEARER can still authenticate with a token by presenting it as a password. Refer to [Cluster Single Sign-on (SSO) using JWTs](/docs/v26.4/sso-sql). ## Manage auto-provisioned users When automatic user provisioning is enabled, you can identify and manage auto-provisioned users with the following methods. For additional patterns, such as finding dormant accounts and cleaning up users removed from your IdP, refer to [Manage auto-provisioned users](/docs/v26.4/ldap-authentication#manage-auto-provisioned-users) on the LDAP authentication page; the same statements apply with an `oauth:` source. ### View provisioned users Auto-provisioned users can be identified by their `PROVISIONSRC` role option using the [`SHOW USERS WITH SOURCE`](/docs/v26.4/show-users) syntax: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SHOW USERS WITH SOURCE = 'oauth:https://auth.example.com'; ``` ``` username | options | member_of | estimated_last_login_time -----------+----------------------------------------------+--------------+-------------------------------- alice | {PROVISIONSRC=oauth:https://auth.example.com} | {developers} | 2026-09-14 19:18:00.201402+00 bob | {PROVISIONSRC=oauth:https://auth.example.com} | {analysts} | 2026-09-13 14:22:15.102938+00 (2 rows) ``` Replace `https://auth.example.com` with your issuer URL. The source must match the full `PROVISIONSRC` value exactly; pattern matching is not supported. ### Bulk-drop dormant provisioned users To de-provision auto-provisioned users at scale, use [`DROP PROVISIONED ROLES`](/docs/v26.4/drop-provisioned-roles). For example, to drop up to 100 users that were provisioned by your issuer and have not logged in since a specific date: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} DROP PROVISIONED ROLES WITH SOURCE = 'oauth:https://auth.example.com', LAST LOGIN BEFORE '2026-01-01' LIMIT 100; ``` Preview the matching users first by running [`SHOW USERS`](/docs/v26.4/show-users) with the same clauses. ### Restrictions on auto-provisioned users Users created through automatic provisioning have specific restrictions: * **Password changes**: Auto-provisioned users cannot change their own passwords using `ALTER USER`, even if the cluster setting `sql.auth.change_own_password.enabled` is `true`. * **`PROVISIONSRC` modification**: The `PROVISIONSRC` role option cannot be modified or removed once set. * **Authentication method**: These users must authenticate through their IdP; password-based authentication is not available. ## How it works ### Authentication sequence 1. **SASL exchange**: The client connects over TLS. If an `oauth` HBA rule matches, the server advertises the `OAUTHBEARER` mechanism and the client sends an RFC 7628 initial response containing `auth=Bearer `. 2. **Identity mapping**: The node parses the token and, before verifying it, reads the claim named by `server.oauthbearer_authentication.claim` (or `sub`), applies the identity map named by the rule's `map=` option if any, and confirms that the result includes the SQL user the client requested and is not a reserved identity. 3. **Provisioning**: If the user does not exist and `security.provisioning.oauth.enabled` is `true`, the node verifies the token's signature against the issuer's JWKS (static or auto-fetched) and checks that its `iss` claim is one of the configured issuers, then creates the user with `PROVISIONSRC = oauth:`. 4. **Token validation**: The node confirms that the token's `iss` claim is one of the configured issuers (and matches the rule's `issuer=` option, if set), verifies the signature against the issuer's JWKS, and checks the expiry and the `aud` claim against `server.oauthbearer_authentication.audience`. With automatic fetching enabled, the node fetches the issuer's discovery document and JWKS on every login; keys are not cached. 5. **Role synchronization**: If `server.oauthbearer_authentication.authorization.enabled` is `true`, the node reconciles the user's direct role memberships with the groups in the token. ### Error response When a token is missing or rejected, the server replies with an `AuthenticationSASLContinue` message whose body is the JSON error response defined in [RFC 7628 §3.2.2](https://www.rfc-editor.org/rfc/rfc7628#section-3.2.2): ```json theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} {"status":"invalid_token","scope":"openid email","openid-configuration":"https://auth.example.com/.well-known/openid-configuration"} ``` | Field | Meaning | | - | - | | `status` | Always `invalid_token`. | | `scope` | The value of `server.oauthbearer_authentication.scope`. Omitted when that setting is empty. | | `openid-configuration` | The OpenID configuration endpoint of the configured issuer. Included only when exactly one issuer is configured in `server.oauthbearer_authentication.issuers`. | Discovery-driven clients such as `libpq` deliberately send an empty token first to receive this response, then use the `openid-configuration` and `scope` values to obtain a token and reconnect. After sending the response, the server waits briefly for the client's acknowledgement and then closes the connection with a generic authentication error. The detailed reason for the rejection is written only to the [`SESSIONS`](/docs/v26.4/logging#sessions) log, so that unauthenticated clients cannot learn about your configuration or which users exist. Malformed SASL messages, such as a request for channel binding (`OAUTHBEARER-PLUS`) or a non-empty authorization identity, are framing errors: the connection fails without an error response. ## Troubleshooting Enable [`SESSIONS` logging](/docs/v26.4/logging#sessions) to preserve data that will help troubleshoot OAUTHBEARER issues: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.auth_log.sql_sessions.enabled = true; ``` > [!NOTE] > > Once all functionality is configured and tested successfully, Cockroach Labs recommends disabling session logging to conserve system resources. To view the logs, open `cockroach-sql-auth.log` from your [logging directory](/docs/v26.4/configure-logs#logging-directory). Clients receive only a generic error; the specific cause is in the log. Potential issues to investigate may pertain to: * **`ObjectNotInPrerequisiteState` when setting the HBA configuration**: The cluster is not yet fully upgraded to v26.4. Finish the upgrade and finalize it, then set the `oauth` rule. * **`method "oauth" required for this user, but unusable over this connection type`**: The client connected without TLS. Connect with `sslmode=verify-full`. * **Invalid issuer**: The token's `iss` claim is not in `server.oauthbearer_authentication.issuers`, or does not match the `issuer=` option on the matching HBA rule. * **Invalid audience**: The token's `aud` claim does not contain a value in `server.oauthbearer_authentication.audience`, or that setting is empty. Configure the IdP to issue tokens with an audience for CockroachDB and set the setting to match. * **Signing key not found**: With static keys, `server.oauthbearer_authentication.jwks` does not contain the key that signed the token. With automatic fetching, the node could not reach the issuer's JWKS endpoint, possibly because of a private CA (set `server.oauthbearer_authentication.issuers.custom_ca`) or a timeout (`server.oauthbearer_authentication.client.timeout`). * **Token principal does not map to the requested user**: The claim named by `server.oauthbearer_authentication.claim` is missing from the token (the login fails with a missing-claim error; `sub` is used only when that setting is empty), or the identity map does not translate it to the SQL user the client requested. Check the `map=` option on the HBA rule and the lines in `server.identity_map.configuration`. * **User does not exist**: The mapped user has not been created and `security.provisioning.oauth.enabled` is `false`. * **`refusing to send an OAuth token over a plaintext connection`**: `cockroach sql` was run with the device flow but without `sslmode=verify-full`. * **Issuer must use `https`**: The device flow in `cockroach sql` rejected a plaintext issuer or endpoint. Use an HTTPS issuer, or for local development only, set `COCKROACH_OAUTH_ALLOW_INSECURE_ISSUER=true`. * **`psql` cannot discover the issuer**: More than one issuer is configured, so the server does not advertise an `openid-configuration` endpoint. Use a single issuer, or use a client that is told the issuer explicitly. * **Empty group list or userinfo lookup failed**: Group-based authorization is enabled and the user has no groups in the token, or the userinfo endpoint could not be queried. Refer to [Step 5](#step-5-enable-group-based-authorization-optional). ## Security considerations 1. **Trust only known issuers**: Any valid token from an issuer in `server.oauthbearer_authentication.issuers` can log in as, and with provisioning enabled create, a SQL user. Keep the list minimal, and use the `issuer=` HBA option to restrict which issuer applies to which users. 2. **Restrict the audience**: Set `server.oauthbearer_authentication.audience` to a value that your IdP issues only for CockroachDB, so that tokens minted for other services cannot be replayed against the cluster. 3. **Prefer automatic key fetching**: Enable `server.oauthbearer_authentication.jwks_auto_fetch.enabled` so that key rotation at the IdP cannot lock users out or leave stale keys trusted, and set `server.oauthbearer_authentication.issuers.custom_ca` rather than disabling TLS verification when the IdP uses a private CA. 4. **Require verified TLS on clients**: Bearer tokens are credentials. `cockroach sql` enforces `sslmode=verify-full`; configure other clients the same way. 5. **Maintain backup authentication**: Keep a password or certificate for administrative users so that an IdP outage does not lock you out. `root` cannot use OAUTHBEARER. 6. **Review provisioned users and synchronized roles**: Audit `SHOW USERS WITH SOURCE` regularly, and remember that group-based authorization synchronizes every matching role, including `admin`. 7. **Tokens are not stored**: CockroachDB validates each token in memory and does not persist it. Keep token lifetimes short at the IdP. ## See also * [Cluster Single Sign-on (SSO) using JWTs](/docs/v26.4/sso-sql) * [JWT Authorization](/docs/v26.4/jwt-authorization) * [LDAP Authentication](/docs/v26.4/ldap-authentication) * [SQL Authentication](/docs/v26.4/security-reference/authentication) * [`cockroach sql`](/docs/v26.4/cockroach-sql) * [Cluster Settings](/docs/v26.4/cluster-settings) * [`CREATE USER`](/docs/v26.4/create-user) * [`SHOW USERS`](/docs/v26.4/show-users) * [`DROP PROVISIONED ROLES`](/docs/v26.4/drop-provisioned-roles) # Configure OIDC Authorization for DB Console Source: https://docs.cockroachlabs.com/docs/stable/oidc-authorization > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). If you manage users through an identity provider (IdP) that supports OpenID Connect (OIDC), you can configure CockroachDB to automatically assign [roles](/docs/v26.4/security-reference/authorization) to users based on group claims when they log into the DB Console, simplifying access control. If OIDC authorization is enabled: 1. When a user logs into the DB Console using OIDC, the cluster extracts the groups claim from the ID token. 2. If the groups claim is not present in the ID token, the cluster checks the access token (if it's a JWT). 3. If neither token yields any groups, the cluster queries the IdP's userinfo endpoint as a fallback. 4. Each group is mapped to a cluster role by matching the group name to a role name. 5. The user is granted each corresponding role, and roles that the user holds directly but that no longer match the user's groups are revoked. Roles held only indirectly through another role are not revoked individually. Refer to [Role synchronization](#role-synchronization). ## Prerequisites * Enable [OIDC Authentication for DB Console](/docs/v26.4/sso-db-console). * Understand the structure of tokens issued by your identity provider. * Know which claim in your tokens contains group memberships. ## Configuration Before you begin, it may be useful to enable authentication logging, which can help you confirm successful configuration or troubleshoot issues. For details, refer to [Troubleshooting](#troubleshooting). ### Step 1: Enable OIDC authorization Enable OIDC authorization and configure the groups claim: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Enable OIDC authorization SET CLUSTER SETTING server.oidc_authentication.authorization.enabled = true; -- Configure the claim containing groups (default: 'groups') SET CLUSTER SETTING server.oidc_authentication.group_claim = 'groups'; -- (Optional) Configure the userinfo endpoint JSON key for groups fallback SET CLUSTER SETTING server.oidc_authentication.userinfo_group_key = 'groups'; ``` > [!NOTE] > > The `userinfo_group_key` setting is only used when neither the ID token nor the access token yields any groups, either because the groups claim is missing from both or because it is present but empty. CockroachDB will query the IdP's userinfo endpoint using this key to retrieve group memberships. ### Step 2: Create matching roles [Create CockroachDB roles](/docs/v26.4/create-user) that match your IdP group names and grant appropriate privileges to each role. Remember that role names must comply with CockroachDB's [identifier requirements](/docs/v26.4/create-user#user-names). > [!NOTE] > > Group names from the IdP are normalized using case folding and Unicode normalization (NFC) before matching to role names. This means that group names are typically converted to lowercase for matching purposes. For example, if your OIDC tokens contain groups named `developers` and `analysts`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- Create role for developers CREATE ROLE developers; GRANT ALL ON DATABASE app TO developers; -- Create role for analysts CREATE ROLE analysts; GRANT SELECT ON DATABASE analytics TO analysts; ``` ### Step 3: Confirm configuration 1. On your identity provider, set up test users with memberships in groups that should be synced to CockroachDB roles. 2. Navigate to the DB Console in your web browser and log in using OIDC. Refer to [Log in to a cluster's DB Console with SSO](/docs/v26.4/sso-db-console). 3. Using your `admin` credentials in a SQL shell, verify the user's role assignments: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} -- View roles granted to a specific user SHOW GRANTS FOR alice; -- Check if user has a specific role SELECT pg_has_role('alice', 'developers', 'member'); ``` ## How it works ### Group extraction process When a user authenticates with OIDC and OIDC authorization is enabled: 1. **Token validation**: CockroachDB validates the ID token signature, issuer, and claims. 2. **Group extraction from ID token**: CockroachDB looks for the configured `group_claim` (default: `groups`) in the ID token. 3. **Group extraction from access token**: If the groups claim is not found in the ID token, CockroachDB checks the access token (if it's a JWT format) for the same claim. 4. **Userinfo endpoint fallback**: If the ID token and access token yield no groups, either because the claim is not present in either token or because it is present but contains an empty list, CockroachDB queries the IdP's userinfo endpoint and looks for the `userinfo_group_key` (default: `groups`). Some identity providers return an empty array in the token and populate groups only in the userinfo response. 5. **Combine and deduplicate**: Groups from the ID token and access token are combined and deduplicated. Groups from the userinfo endpoint are processed separately. 6. **Normalization**: Group names are normalized using `MakeSQLUsernameFromUserInput`, which performs case folding and Unicode normalization (NFC). 7. **Role matching**: Each normalized group name is compared against existing CockroachDB roles. > [!NOTE] > > **Groups claim format**: The groups claim is expected to be a JSON array of strings, for example `["developers", "analysts"]`. If the claim is a single string instead, CockroachDB splits it on commas only, so `"developers,analysts"` yields two groups, while a group name that contains spaces, such as `"data platform"`, is treated as one group. Each name is trimmed of surrounding whitespace and lowercased, empty entries are dropped, and duplicates are removed. The same parsing applies to the value of `userinfo_group_key` in the userinfo response. Identity providers that convey multiple groups should return a JSON array. > [!NOTE] > > OIDC authorization checks three sources for groups: ID token, access token, and userinfo endpoint. Groups from the ID token and access token are combined into a single list, while userinfo groups are treated as a separate fallback that is consulted only when that combined list is empty. ### Role synchronization On each DB Console login, CockroachDB synchronizes the user's role memberships: 1. **Grant new roles**: If a group matches an existing role name and the user doesn't already have that role, it is granted. 2. **Revoke stale roles**: If the user [directly](/docs/v26.4/security-reference/authorization#direct-member) holds roles that don't match any current groups, those roles are revoked. Only the user's direct role memberships are reconciled; roles the user holds [indirectly](/docs/v26.4/security-reference/authorization#indirect-member) through a directly granted role are not revoked individually. For example, if the user was directly granted `developers`, and `developers` is itself a member of `app_readers`, the user holds `app_readers` indirectly. If the IdP then lists only `app_readers`, CockroachDB revokes `developers` and grants `app_readers` directly. 3. **Skip non-existent roles**: If a group doesn't match any existing role, it is silently skipped (no error is raised). > [!NOTE] > > IdP groups that don't correspond to CockroachDB roles are silently ignored. You must pre-create roles in CockroachDB for them to be granted. ### Empty groups behavior If the groups claim exists but contains an empty array (`[]`), and no other source yields any groups: 1. All role memberships that the user holds directly are revoked. 2. Login is **rejected** with error: `OIDC: unable to complete authentication: groups list was empty for ` This behavior ensures that users without group memberships cannot access the cluster, which is a security feature to prevent unauthorized access. ### Missing groups claim If the configured groups claim cannot be found in the ID token, the access token, or the userinfo response (for example, because the claim name is misconfigured, the IdP was not asked for the scope that emits groups, or the IdP transiently failed to return the claim): 1. The user's existing role memberships are left unchanged. 2. Login is **rejected** with error: `OIDC: unable to complete authentication: no groups claim found for ` A missing claim is treated as a failure to determine the user's groups, not as a statement that the user belongs to no groups, so a transient IdP problem does not revoke the user's roles. The following table summarizes the difference between an empty and a missing groups claim: | Groups claim | Role memberships | Login | | - | - | - | | Present but empty (`[]`) | Directly held roles are revoked | Rejected | | Not found in any source | Unchanged | Rejected | ## Troubleshooting Enable [`SESSION` logging](/docs/v26.4/logging#sessions) to preserve data that will help troubleshoot OIDC authorization issues: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SET CLUSTER SETTING server.auth_log.sql_sessions.enabled = true; ``` > [!NOTE] > > Once all functionality is configured and tested successfully, we recommend disabling session logging to conserve system resources. To view the logs, open `cockroach-sql-auth.log` from your [logging directory](/docs/v26.4/configure-logs#logging-directory). Potential issues to investigate may pertain to: * **Token validation**: Ensure the ID token is properly signed and issued by a trusted issuer. * **Missing groups claim**: Check if the ID token or access token contains the configured claim name. Use a JWT decoder tool to inspect the tokens. If the claim cannot be found in any source, the login is rejected and the user's roles are not modified. * **Claim name mismatch**: Verify that `server.oidc_authentication.group_claim` matches the actual claim name in your tokens. * **Userinfo endpoint**: If relying on userinfo fallback, ensure the endpoint is accessible and returns the expected JSON structure. * **Role name mismatches**: Remember that group names are normalized (typically lowercased). Check that your role names match the normalized group names. * **Empty groups**: Verify that users have group memberships in the IdP. An explicitly empty groups list revokes the user's directly held roles and rejects the login. * **User doesn't exist**: Ensure the user has been created in CockroachDB before attempting to log in, or enable [automatic user provisioning](/docs/v26.4/sso-db-console#manage-auto-provisioned-users). With OIDC authorization enabled, authorization runs before the login step, so a missing user fails authorization first (either no groups claim is found, or role synchronization reports that the role does not exist) and the browser receives a `403` error. The [`client_authentication_failed`](/docs/v26.4/eventlog#client_authentication_failed) event with `Reason` set to `USER_NOT_FOUND` described in [Audit failed SSO logins](/docs/v26.4/sso-db-console#audit-failed-sso-logins) is written only when OIDC authorization is disabled. ### Common errors **Error**: `OIDC: unable to complete authentication: groups list was empty for ` * **Cause**: The groups claim exists but contains an empty array. The user's directly held roles have been revoked. * **Solution**: Ensure users have appropriate group memberships in your identity provider. **Error**: `OIDC: unable to complete authentication: no groups claim found for ` * **Cause**: The configured groups claim was not found in the ID token, the access token, or the userinfo response. The user's role memberships were not modified. * **Solution**: Verify that `server.oidc_authentication.group_claim` and `server.oidc_authentication.userinfo_group_key` match the claim name your IdP uses, and that `server.oidc_authentication.scopes` includes the scope your IdP requires to emit group information. If the configuration is correct, the failure may be transient; retry the login. **Error**: User can log in but has no privileges * **Cause**: Groups from the IdP don't match any existing CockroachDB roles. * **Solution**: Create roles with names matching the normalized group names from your IdP. **Error**: User not found * **Cause**: The user doesn't exist in CockroachDB and automatic user provisioning is not enabled. * **Log entry**: With OIDC authorization enabled, the failure surfaces as an authorization error (no groups claim found, or a role synchronization error that the role does not exist) rather than as a [`client_authentication_failed`](/docs/v26.4/eventlog#client_authentication_failed) event with `Reason` set to `USER_NOT_FOUND`. That event is emitted only when OIDC authorization is disabled. For details, refer to [Audit failed SSO logins](/docs/v26.4/sso-db-console#audit-failed-sso-logins). * **Solution**: Either create the user in CockroachDB manually before they attempt to log into the DB Console, or enable [automatic user provisioning](/docs/v26.4/sso-db-console#manage-auto-provisioned-users). ## Security considerations 1. **Maintain backup authentication**: Always keep a backup authentication method (like password) for administrative users in case of IdP outages. 2. **Validate token issuers**: Ensure your OIDC configuration only accepts tokens from trusted issuers. 3. **Pre-create roles with minimal privileges**: Create roles before enabling authorization and grant only the necessary privileges following the principle of least privilege. 4. **Monitor role synchronization**: Regularly audit role assignments and changes. Enable audit logging if available to track when roles are granted or revoked. 5. **Secure the userinfo endpoint**: If using userinfo fallback, ensure the endpoint requires proper authentication and is only accessible over HTTPS. 6. **Review empty groups policy**: Understand that empty groups will block login. Ensure this aligns with your security requirements. 7. **Regularly audit IdP groups**: Review and clean up group memberships in your identity provider to ensure they reflect current access requirements. 8. **User provisioning**: If using [automatic user provisioning](/docs/v26.4/sso-db-console#manage-auto-provisioned-users), ensure your OIDC provider is properly secured and only trusted users can authenticate. Regularly review auto-provisioned users to identify accounts that may need deprovisioning. If not using automatic provisioning, ensure all users are created in CockroachDB before they need access to the DB Console. ## See also * [Single sign-on (SSO) to DB Console](/docs/v26.4/sso-db-console) * [JWT Authorization](/docs/v26.4/jwt-authorization) * [LDAP Authorization](/docs/v26.4/ldap-authorization) * [Authorization](/docs/v26.4/security-reference/authorization) # Orchestrate CockroachDB Across Multiple Kubernetes Clusters Source: https://docs.cockroachlabs.com/docs/stable/orchestrate-cockroachdb-with-kubernetes-multi-cluster This page shows you how to orchestrate a secure CockroachDB deployment across three [Kubernetes](http://kubernetes.io/) clusters, each in a different geographic region, using [StatefulSets](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) to manage the containers within each cluster and linking them together via DNS. This will result in a single, multi-region CockroachDB cluster running on Kubernetes. > [!CAUTION] > > This page describes a Kubernetes deployment method that is considered "legacy" and will not be supported in a future release of CockroachDB. New CockroachDB deployments on Kubernetes are recommended to use the newer, fully-featured [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) that's easier to deploy and supports scaling of multi-region clusters. To migrate an existing deployment to use the CockroachDB operator, read the [Helm](/docs/v26.4/migrate-cockroachdb-kubernetes-helm) and [Public operator](/docs/v26.4/migrate-cockroachdb-kubernetes-operator) migration guides. > > For more information on legacy Kubernetes deployments and support timelines, read the [deprecation notice](/docs/v26.4/kubernetes-deprecation-notice). To deploy CockroachDB in a single Kubernetes cluster instead, see [Kubernetes Single-Cluster Deployment](/docs/v26.4/deploy-cockroachdb-with-kubernetes). Also, for details about potential performance bottlenecks to be aware of when running CockroachDB in Kubernetes and guidance on how to optimize your deployment for better performance, see [CockroachDB Performance on Kubernetes](/docs/v26.4/kubernetes-performance). **GKE** ## Before you begin Before getting started, it's helpful to review some Kubernetes-specific terminology and current limitations. * [Kubernetes terminology](#kubernetes-terminology) * [UX differences from running in a single cluster](#ux-differences-from-running-in-a-single-cluster) * [Best practices](#best-practices) ### Kubernetes terminology | Feature | Description | | - | - | | [node](https://kubernetes.io/docs/concepts/architecture/nodes/) | A physical or virtual machine. In this tutorial, you'll run GKE or EKS instances and join them as worker nodes in three independent Kubernetes clusters, each in a different region. | | [pod](http://kubernetes.io/docs/user-guide/pods/) | A pod is a group of one or more Docker containers. In this tutorial, each pod will run on a separate GKE or EKS instance and include one Docker container running a single CockroachDB node. You'll start with 3 pods in each region and grow to 4. | | [StatefulSet](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) | A group of pods treated as stateful units, where each pod has distinguishable network identity and always binds back to the same persistent storage on restart. StatefulSets are considered stable as of Kubernetes version 1.9 after reaching beta in version 1.5. | | [persistent volume](http://kubernetes.io/docs/user-guide/persistent-volumes/) | A piece of networked storage (Persistent Disk on GCE, Elastic Block Store on AWS) mounted into a pod. The lifetime of a persistent volume is decoupled from the lifetime of the pod that's using it, ensuring that each CockroachDB node binds back to the same storage on restart. This tutorial assumes that dynamic volume provisioning is available. When that is not the case, [persistent volume claims](http://kubernetes.io/docs/user-guide/persistent-volumes/#persistentvolumeclaims) need to be created manually. | | [CSR](https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster/) | A CSR, or certificate signing request, is a request to have a TLS certificate verified by a certificate authority (CA). A CSR is issued for the CockroachDB node running in each pod, as well as each client as it connects to the Kubernetes cluster. | | [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) | RBAC, or role-based access control, is the system Kubernetes uses to manage permissions within the cluster. In order to take an action (e.g., `get` or `create`) on an API resource (e.g., a `pod`), the client must have a `Role` that allows it to do so. | | [namespace](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) | A namespace provides a scope for resources and names within a Kubernetes cluster. Names of resources must be unique within a namespace, but not across namespaces. Most Kubernetes client commands will use the `default` namespace by default, but can operate on resources in other namespaces as well. In this tutorial, CockroachDB pods will be deployed in their own namespace in each Kubernetes cluster. | | [kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) | `kubectl` is the command-line interface for running commands against Kubernetes clusters. | | [kubectl context](https://kubernetes.io/docs/reference/kubectl/cheatsheet/#kubectl-context-and-configuration) | When multiple Kubernetes clusters are deployed on your account, `kubectl` "context" specifies a cluster to connect to. | ### UX differences from running in a single cluster These instructions create 3 StatefulSets that each run 3 CockroachDB pods in a separate Kubernetes cluster deployed in its own region. If you haven't often worked with multiple Kubernetes clusters, remember that `kubectl` commands are run against a cluster in a specific context. Either run `kubectl use-context ` frequently to switch contexts between commands, or append `--context ` to the commands you run to ensure they are run against the correct cluster. Each Kubernetes cluster's DNS server is pointed at the other clusters' DNS servers so that DNS lookups for certain zone-scoped suffixes (e.g., `*.us-west1-a.svc.cluster.local`) can be deferred to the appropriate cluster's DNS server. To make this work, we create the StatefulSets in namespaces named after the region in which each Kubernetes cluster is deployed. To run a command against one of the pods, append `--namespace ` to your commands. Alternatively, run `kubectl config set-context --namespace ` to set the default namespace for a context. Because the CockroachDB pods run in a non-default namespace, client applications wanting to talk to CockroachDB from the default namespace would need to use a zone-scoped service name (e.g., `cockroachdb-public.us-west1-a`) rather than `cockroachdb-public`, as in a single-cluster setting. However, the setup script used by these instructions sets up an additional [`ExternalName` service](https://kubernetes.io/docs/concepts/services-networking/service/#externalname) in the default namespace such that the clients in the default namespace can simply talk to the `cockroachdb-public` address. ### Best practices #### Kubernetes version To deploy CockroachDB v26.4, Kubernetes 1.18 or higher is required. Cockroach Labs strongly recommends that you use a Kubernetes version that is [eligible for patch support by the Kubernetes project](https://kubernetes.io/releases/). #### Public operator * The Public operator deploys clusters in a single region. For multi-region deployments using manual configs, Cockroach Labs recommends using the [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) which is designed to support multi-region deployments. For guidance on how to force multi-region support with the Public operator, see [Orchestrate CockroachDB Across Multiple Kubernetes Clusters](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster). * Using the Public operator, you can give a new cluster an arbitrary number of [labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/). However, a cluster's labels cannot be modified after it is deployed. To track the status of this limitation, refer to [#993](https://github.com/cockroachdb/cockroach-operator/issues/993) in the Public operator project's issue tracker. #### Helm version The CockroachDB Helm chart requires Helm 3.0 or higher. If you attempt to use an incompatible Helm version, an error like the following occurs: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Error: UPGRADE FAILED: template: cockroachdb/templates/tests/client.yaml:6:14: executing "cockroachdb/templates/tests/client.yaml" at <.Values.networkPolicy.enabled>: nil pointer evaluating interface {}.enabled ``` The public Helm chart is currently not under active development, and no new features are planned. However, Cockroach Labs remains committed to fully supporting the Helm chart by addressing defects, providing security patches, and addressing breaking changes due to deprecations in Kubernetes APIs. A deprecation notice for the public Helm chart will be provided to customers a minimum of 6 months in advance of actual deprecation. #### Network Service Name Indication (SNI) is an extension to the TLS protocol which allows a client to indicate which hostname it is attempting to connect to at the start of the TCP handshake process. The server can present multiple certificates on the same IP address and TCP port number, and one server can serve multiple secure websites or API services even if they use different certificates. Due to its order of operations, the PostgreSQL wire protocol's implementation of TLS is not compatible with SNI-based routing in the Kubernetes ingress controller. Instead, use a TCP load balancer for CockroachDB that is not shared with other services. #### Resources When starting Kubernetes, select machines with at least **4 vCPUs** and **16 GiB** of memory, and provision at least **2 vCPUs** and **8 Gi** of memory to CockroachDB per pod. These minimum settings are used by default in this deployment guide, and are appropriate for testing purposes only. On a production deployment, you should adjust the resource settings for your workload. For details, see [Resource management](/docs/v26.4/configure-cockroachdb-kubernetes#memory-and-cpu). #### Storage Kubernetes deployments use external persistent volumes that are often replicated by the provider. CockroachDB replicates data automatically, and this redundant layer of replication can impact performance. Using [local volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local) may improve performance. #### Exposing DNS servers > [!CAUTION] > > Instead of using this approach, you can now [enable global access](https://cloud.google.com/load-balancing/docs/internal/setting-up-internal#ilb-global-access), which exposes the Kubernetes cluster's DNS servers via a load-balanced IP address that is visible to the public internet. With this this approach, noone of the services in your Kubernetes cluster will be accessible publicly, but their names could leak out to a motivated attacker. ## Step 1. Start Kubernetes clusters Our multi-region deployment approach relies on pod IP addresses being routable across three distinct Kubernetes clusters and regions. Both the hosted Google Kubernetes Engine (GKE) and Amazon Elastic Kubernetes Service (EKS) satisfy this requirement. 1. Complete the **Before You Begin** steps described in the [Google Kubernetes Engine Quickstart](https://cloud.google.com/kubernetes-engine/docs/quickstart) documentation. This includes installing `gcloud`, which is used to create and delete Kubernetes Engine clusters, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. 2. From your local workstation, start the first Kubernetes cluster, specifying the [zone](https://cloud.google.com/compute/docs/regions-zones/) it should run in: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters create cockroachdb1 --zone= [!NOTE] > > The process can take a few minutes, so do not move on to the next step until you see a `Creating cluster cockroachdb1...done` message and details about your cluster. 1. Start the second Kubernetes cluster, specifying the [zone](https://cloud.google.com/compute/docs/regions-zones/) it should run in: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters create cockroachdb2 --zone= [!NOTE] > > `kubectl` commands are run against the `CURRENT` context by default. You can change the current context with this command: > > ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > kubectl config use-context > ``` > > When sending commands to another context, you need to use the `--context` flag to specify the context. For clarity, every `kubectl` command in this tutorial uses the `--context` flag to indicate the proper context. 1. Get the email address associated with your Google Cloud account: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud info | grep Account ``` ``` Account: [your.google.cloud.email@example.org] ``` > [!CAUTION] > > This command returns your email address in all lowercase. However, in the next step, you must enter the address using the accurate capitalization. For example, if your address is [YourName@example.com](mailto:YourName@example.com), you must use [YourName@example.com](mailto:YourName@example.com) and not [yourname@example.com](mailto:yourname@example.com). 1. For each Kubernetes cluster, [create the RBAC roles](https://cloud.google.com/kubernetes-engine/docs/how-to/role-based-access-control#prerequisites_for_using_role-based_access_control) CockroachDB needs for running on GKE, using the email address and relevant "context" name from the previous steps: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create clusterrolebinding $USER-cluster-admin-binding --clusterrole=cluster-admin --user= ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create clusterrolebinding $USER-cluster-admin-binding --clusterrole=cluster-admin --user= ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create clusterrolebinding $USER-cluster-admin-binding --clusterrole=cluster-admin --user= ``` ## Step 2. Start CockroachDB 1. Create a directory and download the required script and configuration files into it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir multiregion ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cd multiregion ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -OOOOOO \ https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/client-secure.yaml https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/cluster-init-secure.yaml https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/cockroachdb-statefulset-secure.yaml https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/dns-lb.yaml https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/example-app-secure.yaml https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/external-name-svc.yaml ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -o setup.py https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/setup.py.txt ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -o teardown.py https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/teardown.py.txt ``` 2. Retrieve the `kubectl` "contexts" for your clusters: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl config get-contexts ``` At the top of the `setup.py` script, fill in the `contexts` map with the zones of your clusters and their "context" names, e.g.: ``` contexts = { 'us-east1-b': 'gke_cockroach-shared_us-east1-b_cockroachdb1', 'us-west1-a': 'gke_cockroach-shared_us-west1-a_cockroachdb2', 'us-central1-a': 'gke_cockroach-shared_us-central1-a_cockroachdb3', } ``` 3. In the `setup.py` script, fill in the `regions` map with the zones and corresponding regions of your clusters, for example: ``` $ regions = { 'us-east1-b': 'us-east1', 'us-west1-a': 'us-west1', 'us-central1-a': 'us-central1', } ``` Setting `regions` is optional, but recommended, because it improves CockroachDB's ability to diversify data placement if you use more than one zone in the same region. If you aren't specifying regions, just leave the map empty. 4. If you haven't already, [install CockroachDB locally and add it to your `PATH`](/docs/v26.4/install-cockroachdb-mac). The `cockroach` binary will be used to generate certificates. If the `cockroach` binary is not on your `PATH`, in the `setup.py` script, set the `cockroach_path` variable to the path to the binary. 5. Optionally, to optimize your deployment for better performance, review [CockroachDB Performance on Kubernetes](/docs/v26.4/kubernetes-performance) and make the desired modifications to the `cockroachdb-statefulset-secure.yaml` file. 6. Run the `setup.py` script: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python setup.py ``` As the script creates various resources and creates and initializes the CockroachDB cluster, you'll see a lot of output, eventually ending with `job "cluster-init-secure" created`. 7. Confirm that the CockroachDB pods in each cluster say `1/1` in the `READY` column, indicating that they've successfully joined the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ``` NAMESPACE NAME READY STATUS RESTARTS AGE us-east1-b cockroachdb-0 1/1 Running 0 14m us-east1-b cockroachdb-1 1/1 Running 0 14m us-east1-b cockroachdb-2 1/1 Running 0 14m ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ``` NAMESPACE NAME READY STATUS RESTARTS AGE us-central1-a cockroachdb-0 1/1 Running 0 14m us-central1-a cockroachdb-1 1/1 Running 0 14m us-central1-a cockroachdb-2 1/1 Running 0 14m ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ``` NAMESPACE NAME READY STATUS RESTARTS AGE us-west1-a cockroachdb-0 1/1 Running 0 14m us-west1-a cockroachdb-1 1/1 Running 0 14m us-west1-a cockroachdb-2 1/1 Running 0 14m ``` If you notice that only one of the Kubernetes clusters' pods are marked as `READY`, you likely also need to configure a network firewall rule that will allow the pods in the different clusters to talk to each other. You can run the following command to create a firewall rule allowing traffic on port 26257 (the port used by CockroachDB for inter-node traffic) within your private GCE network. It will not allow any traffic in from outside your private network: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud compute firewall-rules create allow-cockroach-internal --allow=tcp:26257 --source-ranges=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16 ``` ``` Creating firewall...done. NAME NETWORK DIRECTION PRIORITY ALLOW DENY allow-cockroach-internal default INGRESS 1000 tcp:26257 ``` > [!TIP] > > In each Kubernetes cluster, the StatefulSet configuration sets all CockroachDB nodes to write to `stderr`, so if you ever need access to a pod/node's logs to troubleshoot, use `kubectl logs --context --namespace ` rather than checking the log on the persistent volume. ## Step 3. Use the built-in SQL client Use the `client-secure.yaml` file to launch a pod and keep it running indefinitely, specifying the context of the Kubernetes cluster to run it in: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f client-secure.yaml --context ``` ``` pod "cockroachdb-client-secure" created ``` The pod uses the `root` client certificate created earlier by the `setup.py` script. Note that this will work from any of the three Kubernetes clusters as long as you use the correct namespace and context combination. ## Step 4. Access the DB Console To access the cluster's [DB Console](/docs/v26.4/ui-overview): 1. On secure clusters, [certain pages of the DB Console](/docs/v26.4/ui-overview#db-console-access) can only be accessed by `admin` users. Get a shell into the pod with the `cockroach` binary created earlier and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` 2. Assign `roach` to the `admin` role (you only need to do this once): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > GRANT admin TO roach; ``` 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` 4. Port-forward from your local machine to a pod in one of your Kubernetes clusters: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward cockroachdb-0 8080 --context --namespace ``` ``` Forwarding from 127.0.0.1:8080 -> 8080 ``` > [!NOTE] > > The `port-forward` command must be run on the same machine as the web browser in which you want to view the DB Console. If you have been running these commands from a cloud instance or other non-local shell, you will not be able to view the UI without configuring `kubectl` locally and running the above `port-forward` command on your local machine. 1. Go to [https://localhost:8080](https://localhost:8080) and log in with the username and password created in the [Use the built-in SQL client](#step-3-use-the-built-in-sql-client) step. 2. In the UI, check the [**Node List**](/docs/v26.4/ui-cluster-overview-page#node-list) to verify that all nodes are running, open the [**Databases** page](/docs/v26.4/ui-databases-page) to verify that `bank` is listed, and open the [**Network Latency** page](/docs/v26.4/ui-network-latency-page) to see the performance of your CockroachDB cluster across 3 regions. ## Step 5. Simulate datacenter failure One of the major benefits of running a multi-region CockroachDB cluster is that an entire datacenter or region can go down without affecting the availability of the cluster as a whole. To see this in action: 1. Scale down one of the StatefulSets to zero pods, specifying the namespace and context of the Kubernetes cluster where it's running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl scale statefulset cockroachdb --replicas=0 --context --namespace ``` ``` statefulset "cockroachdb" scaled ``` 2. In the DB Console, the **Cluster Overview** will soon show the three nodes from that region as **Suspect**. If you wait for 5 minutes or more, they will be listed as **Dead**. Note that even though there are three dead nodes, the other nodes are all healthy, and any clients using the database in the other regions will continue to work just fine. 3. When you're done verifying that the cluster still fully functions with one of the regions down, you can bring the region back up by running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl scale statefulset cockroachdb --replicas=3 --context --namespace ``` ``` statefulset "cockroachdb" scaled ``` ## Step 6. Maintain the cluster * [Scale the cluster](#scale-the-cluster) * [Upgrade the cluster](#upgrade-the-cluster) * [Stop the cluster](#stop-the-cluster) ### Scale the cluster Each of your Kubernetes clusters contains 3 instances that can run CockroachDB pods. It's easy to scale a cluster to run more pods. To ensure that you do not have two CockroachDB pods on the same instance (as recommended in our [production best practices](/docs/v26.4/recommended-production-settings)), you need to first add a new instance and then edit your StatefulSet configuration to add another pod. 1. [Resize your Kubernetes cluster.](https://cloud.google.com/kubernetes-engine/docs/how-to/resizing-a-cluster) 2. Use the `kubectl scale` command to add a pod to the StatefulSet in the Kubernetes cluster where you want to add a CockroachDB node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl scale statefulset cockroachdb --replicas=4 --context --namespace ``` ``` statefulset "cockroachdb" scaled ``` 3. Verify that a fourth pod was added successfully: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --context --namespace ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-0 1/1 Running 0 1h cockroachdb-1 1/1 Running 0 1h cockroachdb-2 1/1 Running 0 7m cockroachdb-3 1/1 Running 0 44s cockroachdb-client-secure 1/1 Running 0 26m ``` ### Upgrade the cluster We strongly recommend that you regularly upgrade your CockroachDB version in order to pick up bug fixes, performance improvements, and new features. The upgrade process on Kubernetes is a [staged update](https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/#staging-an-update) in which the Docker image is applied to the pods one at a time, with each pod being stopped and restarted in turn. This is to ensure that the cluster remains available during the upgrade. 1. Verify that you can upgrade. To upgrade to a new major version, you must first be on a production release of the previous version. The release does not need to be the latest production release of the previous version, but it must be a production [release](/docs/releases/index) and not a testing release (alpha/beta). Therefore, in order to upgrade to v26.4, you must be on a production release of . 1. If you are upgrading to v26.4 from a production release earlier than v26.3, or from a testing release (alpha/beta), first [upgrade to a production release of v26.3](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster#upgrade-the-cluster). Be sure to complete all the steps. 2. Then return to this page and perform a second upgrade to v26.4. 3. If you are upgrading from any production release of , or from any earlier v26.4 release, you do not have to go through intermediate releases; continue to step 2. 2. Verify the overall health of your cluster using the [DB Console](/docs/v26.4/ui-overview). On the **Overview**: * Under **Node Status**, make sure all nodes that should be live are listed as such. If any nodes are unexpectedly listed as suspect or dead, identify why the nodes are offline and either restart them or decommission them before beginning your upgrade. If there are dead and non-decommissioned nodes in your cluster, it will not be possible to finalize the upgrade (either automatically or manually). * Under **Replication Status**, make sure there are 0 under-replicated and unavailable ranges. Otherwise, performing a rolling upgrade increases the risk that ranges will lose a majority of their replicas and cause cluster unavailability. Therefore, it's important to identify and resolve the cause of range under-replication and/or unavailability before beginning your upgrade. * In the **Node List**: * Make sure all nodes are on the same version. If any nodes are behind, upgrade them to the cluster's current version first, and then start this process over. * Make sure capacity and memory usage are reasonable for each node. Nodes must be able to tolerate some increase in case the new version uses more resources for your workload. Also go to **Metrics > Dashboard: Hardware** and make sure CPU percent is reasonable across the cluster. If there's not enough headroom on any of these metrics, consider [adding nodes](#scale-the-cluster) to your cluster before beginning your upgrade. 3. Review the backward-incompatible changes in v26.4 and deprecated features. If any affect your deployment, make the necessary changes before starting the rolling upgrade to v26.4. 4. Decide how the upgrade will be finalized. By default, after all nodes are running the new version, the upgrade process will be **auto-finalized**. This will enable certain features and performance improvements introduced in v26.4. After finalization, however, it will no longer be possible to perform a downgrade to . In the event of a catastrophic failure or corruption, the only option is to start a new cluster using the old binary and then restore from a [backup](/docs/v26.4/take-full-and-incremental-backups) created prior to the upgrade. For this reason, **we recommend disabling auto-finalization** so you can monitor the stability and performance of the upgraded cluster before finalizing the upgrade, but note that you will need to follow all of the subsequent directions, including the manual finalization in a later step. > [!NOTE] > > Finalization only applies when performing a major version upgrade (for example, from .x to v26.4). Patch version upgrades (for example, within the v26.4.x series) can always be downgraded. 1. Get a shell into the pod with the `cockroach` binary created earlier and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` 2. Set the `cluster.preserve_downgrade_option` [cluster setting](/docs/v26.4/cluster-settings): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SET CLUSTER SETTING cluster.preserve_downgrade_option = '21.1'; ``` 3. For each Kubernetes cluster, kick off the upgrade process by changing the desired Docker image. To do so, pick the version that you want to upgrade to, then run the following command, replacing "VERSION" with your desired new version and specifying the relevant namespace and "context" name for the Kubernetes cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch statefulset cockroachdb --namespace --context --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"cockroachdb/cockroach:VERSION"}]' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch statefulset cockroachdb --namespace --context --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"cockroachdb/cockroach:VERSION"}]' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch statefulset cockroachdb --namespace --context --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"cockroachdb/cockroach:VERSION"}]' ``` 4. If you then check the status of the pods in each Kubernetes cluster, you should see one of them being restarted: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` This will continue until all of the pods have restarted and are running the new image. 5. If you disabled auto-finalization earlier, monitor the stability and performance of your cluster until you are comfortable with the upgrade (generally at least a day). If you decide to roll back the upgrade, repeat the rolling restart procedure with the old binary. > [!NOTE] > > This is only possible when performing a major version upgrade (for example, from .x to v26.4). Patch version upgrades (for example, within the v26.4.x series) are auto-finalized. To finalize the upgrade, re-enable auto-finalization: 1. Get a shell into the pod with the `cockroach` binary created earlier and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` 2. Re-enable auto-finalization: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > RESET CLUSTER SETTING cluster.preserve_downgrade_option; ``` ### Stop the cluster 1. To delete all of the resources created in your clusters, copy the `contexts` map from `setup.py` into `teardown.py`, and then run `teardown.py`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ python teardown.py ``` ``` namespace "us-east1-b" deleted service "kube-dns-lb" deleted configmap "kube-dns" deleted pod "kube-dns-5dcfcbf5fb-l4xwt" deleted pod "kube-dns-5dcfcbf5fb-tddp2" deleted namespace "us-west1-a" deleted service "kube-dns-lb" deleted configmap "kube-dns" deleted pod "kube-dns-5dcfcbf5fb-8csc9" deleted pod "kube-dns-5dcfcbf5fb-zlzn7" deleted namespace "us-central1-a" deleted service "kube-dns-lb" deleted configmap "kube-dns" deleted pod "kube-dns-5dcfcbf5fb-6ngmw" deleted pod "kube-dns-5dcfcbf5fb-lcfxd" deleted ``` 2. Stop each Kubernetes cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ gcloud container clusters delete cockroachdb1 --zone=` frequently to switch contexts between commands, or append `--context ` to the commands you run to ensure they are run against the correct cluster. To enable the pods to communicate across regions, we peer the VPCs in all 3 regions with each other and configure a CoreDNS service in each region to route DNS traffic to the appropriate pods. To make this work, we create the StatefulSets in namespaces named after the region in which each Kubernetes cluster is deployed. To run a command against one of the pods, append `--namespace ` to your commands. Alternatively, run `kubectl config set-context --namespace ` to set the default namespace for a context. ### Best practices #### Kubernetes version To deploy CockroachDB v26.4, Kubernetes 1.18 or higher is required. Cockroach Labs strongly recommends that you use a Kubernetes version that is [eligible for patch support by the Kubernetes project](https://kubernetes.io/releases/). #### Public operator * The Public operator deploys clusters in a single region. For multi-region deployments using manual configs, Cockroach Labs recommends using the [CockroachDB operator](/docs/v26.4/cockroachdb-operator-overview) which is designed to support multi-region deployments. For guidance on how to force multi-region support with the Public operator, see [Orchestrate CockroachDB Across Multiple Kubernetes Clusters](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster). * Using the Public operator, you can give a new cluster an arbitrary number of [labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/). However, a cluster's labels cannot be modified after it is deployed. To track the status of this limitation, refer to [#993](https://github.com/cockroachdb/cockroach-operator/issues/993) in the Public operator project's issue tracker. #### Helm version The CockroachDB Helm chart requires Helm 3.0 or higher. If you attempt to use an incompatible Helm version, an error like the following occurs: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Error: UPGRADE FAILED: template: cockroachdb/templates/tests/client.yaml:6:14: executing "cockroachdb/templates/tests/client.yaml" at <.Values.networkPolicy.enabled>: nil pointer evaluating interface {}.enabled ``` The public Helm chart is currently not under active development, and no new features are planned. However, Cockroach Labs remains committed to fully supporting the Helm chart by addressing defects, providing security patches, and addressing breaking changes due to deprecations in Kubernetes APIs. A deprecation notice for the public Helm chart will be provided to customers a minimum of 6 months in advance of actual deprecation. #### Network Service Name Indication (SNI) is an extension to the TLS protocol which allows a client to indicate which hostname it is attempting to connect to at the start of the TCP handshake process. The server can present multiple certificates on the same IP address and TCP port number, and one server can serve multiple secure websites or API services even if they use different certificates. Due to its order of operations, the PostgreSQL wire protocol's implementation of TLS is not compatible with SNI-based routing in the Kubernetes ingress controller. Instead, use a TCP load balancer for CockroachDB that is not shared with other services. #### Resources When starting Kubernetes, select machines with at least **4 vCPUs** and **16 GiB** of memory, and provision at least **2 vCPUs** and **8 Gi** of memory to CockroachDB per pod. These minimum settings are used by default in this deployment guide, and are appropriate for testing purposes only. On a production deployment, you should adjust the resource settings for your workload. For details, see [Resource management](/docs/v26.4/configure-cockroachdb-kubernetes#memory-and-cpu). #### Storage Kubernetes deployments use external persistent volumes that are often replicated by the provider. CockroachDB replicates data automatically, and this redundant layer of replication can impact performance. Using [local volumes](https://kubernetes.io/docs/concepts/storage/volumes/#local) may improve performance. ## Step 1. Start Kubernetes clusters Our multi-region deployment approach relies on pod IP addresses being routable across three distinct Kubernetes clusters and regions. Both the hosted Google Kubernetes Engine (GKE) and Amazon Elastic Kubernetes Service (EKS) satisfy this requirement. 1. Complete the steps described in the [EKS Getting Started](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) documentation. This includes installing and configuring the AWS CLI and `eksctl`, which is the command-line tool used to create and delete Kubernetes clusters on EKS, and `kubectl`, which is the command-line tool used to manage Kubernetes from your workstation. > [!NOTE] > > If you are running [EKS-Anywhere](https://aws.amazon.com/eks/eks-anywhere/), CockroachDB requires that you [configure your default storage class](https://kubernetes.io/docs/tasks/administer-cluster/change-default-storage-class/) to auto-provision persistent volumes. Alternatively, you can define a custom storage configuration as required by your install pattern. 1. From your local workstation, create three Kubernetes clusters. For each cluster, specify a unique region and a **non-overlapping** IP range for the VPC in CIDR notation (e.g., 10.0.0.0/16). Refer to the AWS documentation for valid [regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) and [CIDR blocks](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#VPC_Sizing). > [!CAUTION] > > In order to enable VPC peering between the regions, the CIDR blocks of the VPCs **must not** overlap. This value cannot change once the cluster has been created, so be sure that your IP ranges do not overlap. > [!TIP] > > To ensure that all 3 nodes can be placed into a different availability zone, you may want to first [confirm that at least 3 zones are available in the region](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#availability-zones-describe) for your account. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl create cluster \ --name cockroachdb1 \ --nodegroup-name standard-workers \ --node-type m5.xlarge \ --nodes 3 \ --region \ --vpc-cidr ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl create cluster \ --name cockroachdb2 \ --nodegroup-name standard-workers \ --node-type m5.xlarge \ --nodes 3 \ --region \ --vpc-cidr ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl create cluster \ --name cockroachdb3 \ --nodegroup-name standard-workers \ --node-type m5.xlarge \ --nodes 3 \ --region \ --vpc-cidr ``` Each command creates three EKS instances in a region, one for each CockroachDB node you will deploy. Note that each instance is assigned to a different availability zone in the region. In each region, the EKS instances are joined into a separate Kubernetes cluster: `cockroachdb1`, `cockroachdb2`, and `cockroachdb3`. The `--node-type` flag tells the node pool to use the [`m5.xlarge`](https://aws.amazon.com/ec2/instance-types/) instance type (4 vCPUs, 16 GB memory), which meets our [recommended CPU and memory configuration](/docs/v26.4/recommended-production-settings#basic-hardware-recommendations). > [!NOTE] > > Cluster provisioning usually takes between 10 and 15 minutes. Do not move on to the next step until you see a message like `[✔] EKS cluster "cockroachdb1" in "us-east-1" region is ready` for each cluster. 1. Open the [Amazon EC2 console](https://console.aws.amazon.com/ec2/) and verify that three instances, using the node group name you specified, are running in each region. You will need to toggle between each region in the console. 2. Get the context name for each of the 3 regions. When running `kubectl` commands against each region's cluster, you will need to specify the context name for that region. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl config get-contexts ``` ``` CURRENT NAME CLUSTER AUTHINFO NAMESPACE * maxroach@cockroachdb1.eu-central-1.eksctl.io cockroachdb1.eu-central-1.eksctl.io maxroach@cockroachdb1.eu-central-1.eksctl.io maxroach@cockroachdb2.ca-central-1.eksctl.io cockroachdb2.ca-central-1.eksctl.io maxroach@cockroachdb2.ca-central-1.eksctl.io maxroach@cockroachdb3.eu-north-1.eksctl.io cockroachdb3.eu-north-1.eksctl.io maxroach@cockroachdb3.eu-north-1.eksctl.io ``` > [!NOTE] > > `kubectl` commands are run against the "current" context by default. You can change the current context with `kubectl config use-context `. > > When running commands on another region, you need to use the `--context` flag to specify that region's context. For clarity, every `kubectl` command in this tutorial uses the `--context` flag to indicate the proper context. 1. Create three namespaces, one corresponding to each region. The CockroachDB cluster in each region will run in this namespace. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create namespace --context ``` It's simplest for the namespace and region to have the same name, e.g.: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create namespace eu-central-1 --context maxroach@cockroachdb1.eu-central-1.eksctl.io ``` > [!NOTE] > > `kubectl` commands are run against the namespace named `default` by default. You can change the default namespace for a given context with `kubectl config set-context --namespace `. > > For clarity, every `kubectl` command in this tutorial uses the `--namespace` flag to indicate the proper namespace. ## Step 2. Configure your network ### Set up VPC peering For pods to communicate across three separate Kubernetes clusters, the VPCs in all regions need to be peered. Network traffic can then be routed between the VPCs. For more information about VPC peering, see the [AWS documentation](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html). 1. Open the [Amazon VPC console](https://console.aws.amazon.com/vpc/) and note the ID of the VPC in each region. The VPC ID is found in the section called Your VPCs. 2. Navigate to the Peering Connections section and [create a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#create-vpc-peering-connection-local) between each of the 3 regions. When you create a peering connection, you will first select a requester VPC in the current region and then an accepter VPC in another region, specified by pasting the VPC ID. > [!TIP] > > You need to create a total of 3 VPC peering connections between your 3 VPCs, which means switching regions at least once in the console. For example, if you are deploying in `eu-central-1`, `eu-north-1`, and `ca-central-1`, you can select `eu-central-1` in the console and create VPC peering connections to both `eu-north-1` and `ca-central-1`. Then switch to either `eu-north-1` or `ca-central-1` to create the VPC peering connection between those two regions. 1. To complete the VPC peering connections, switch to each destination region and [accept the pending connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#accept-vpc-peering-connection) in the VPC console. 2. For all 3 regions, navigate to the Route Tables section and find `PublicRouteTable`. [Update this route table](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html) with 2 new entries that point traffic to the other 2 peered VPCs. The **Destination** should be the CIDR block of a destination region, and the **Target** should be the VPC peering connection between the current and the destination region. ### Create inbound rules For each region, navigate to the Security Groups section of the [Amazon EC2 console](https://console.aws.amazon.com/ec2/) and locate the security group that enables communication between nodes in the cluster. It should have a name like `ClusterSharedNodeSecurityGroup`. [Add Custom TCP inbound rules](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html#adding-security-group-rule) to this security group to allow TCP communication on two ports: * `26257` for inter-node and client-node communication. This enables the nodes to work as a cluster, the load balancer to route traffic to the nodes, and applications to connect to the load balancer. * `8080` for exposing the DB Console to the user, and for routing the load balancer to the health check endpoint. > [!NOTE] > > Remember to create these inbound rules in all 3 regions. This enables CockroachDB to communicate across each Kubernetes cluster. #### Inter-region communication | Field | Value | | - | - | | Port Range | **26257** | | Source | The IP range of each region's VPC in CIDR notation (e.g., 10.12.0.0/16) | This important rule enables node communication between Kubernetes clusters in different regions. You need to create a separate rule for each region in your deployment. #### Inter-node and load balancer-node communication | Field | Value | | - | - | | Port Range | **26257** | | Source | The ID of your security group (e.g., *sg-07ab277a*) | #### Application data | Field | Value | | - | - | | Port Range | **26257** | | Source | Your application's IP ranges | #### DB Console | Field | Value | | - | - | | Port Range | **8080** | | Source | Your network's IP ranges | You can set your network IP by selecting "My IP" in the Source field. #### Load balancer-health check communication | Field | Value | | - | - | | Port Range | **8080** | | Source | The IP range of your VPC in CIDR notation (e.g., 10.12.0.0/16) | To get the IP range of a VPC, open the [Amazon VPC console](https://console.aws.amazon.com/vpc/) and find the VPC listed in the section called Your VPCs. ### Set up load balancing The Kubernetes cluster in each region needs to have a [Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html) pointed at its CoreDNS service, which you will configure in the next step. 1. Upload our load balancer manifest [`dns-lb-eks.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/dns-lb-eks.yaml) to the Kubernetes clusters in all 3 regions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/dns-lb-eks.yaml --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/dns-lb-eks.yaml --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl apply -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/dns-lb-eks.yaml --context ``` You should see the load balancer appear in the Load Balancers section of the EC2 console in each region. This load balancer will route traffic to CoreDNS in the region. 2. For each region, navigate to the Load Balancer section of the [EC2 console](https://console.aws.amazon.com/ec2/) and get the DNS name of the Network Load Balancer you created in the previous step. 3. For each region's load balancer, look up the IP addresses mapped to the load balancer's DNS name: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} dig ``` ``` ... ;; ANSWER SECTION: ac63a423fbf6231cba51235e1e51e6ec-132cf6c423e67123.elb.eu-central-1.amazonaws.com. 60 IN A ip1 ac63a423fbf6231cba51235e1e51e6ec-132cf6c423e67123.elb.eu-central-1.amazonaws.com. 60 IN A ip2 ac63a423fbf6231cba51235e1e51e6ec-132cf6c423e67123.elb.eu-central-1.amazonaws.com. 60 IN A ip3 ... ``` `ip1`, `ip2`, and `ip3` correspond to the 3 availability zones in the region where Network Load Balancers have been set up. You will need these IP addresses when configuring your network in the next step. ### Configure CoreDNS Each Kubernetes cluster has a [CoreDNS](https://coredns.io/) service that responds to DNS requests for pods in its region. CoreDNS can also forward DNS requests to pods in other regions. To enable traffic forwarding to CockroachDB pods in all 3 regions, you need to [modify the ConfigMap](https://kubernetes.io/docs/tasks/administer-cluster/dns-custom-nameservers/#coredns-configmap-options) for the CoreDNS Corefile in each region. 1. Download and open our ConfigMap template [`configmap.yaml`](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/configmap.yaml): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/configmap.yaml ``` 2. After [obtaining the IP addresses of the Network Load Balancers](#set-up-load-balancing) in all 3 regions, you can use this information to define a **separate ConfigMap for each region**. Each unique ConfigMap lists the forwarding addresses for the pods in the 2 other regions. ``` ... region2.svc.cluster.local:53 { # <---- Modify log errors ready cache 10 forward . ip1 ip2 ip3 { # <---- Modify force_tcp } } region3.svc.cluster.local:53 { # <---- Modify log errors ready cache 10 forward . ip1 ip2 ip3 { # <---- Modify force_tcp } } ``` For each region, modify `configmap.yaml` by replacing: * `region2` and `region3` with the namespaces in which the CockroachDB pods will run in the other 2 regions. You defined these namespaces after [starting the Kubernetes clusters](#step-1-start-kubernetes-clusters). * `ip1`, `ip2`, and `ip3` with the IP addresses of the Network Load Balancers in the region, which you looked up in the previous step. You will end up with 3 different ConfigMaps. Give each ConfigMap a unique filename like `configmap-1.yaml`. > [!NOTE] > > If you configure your Network Load Balancer to support UDP traffic, you can drop the `force_tcp` line. 1. For each region, first back up the existing ConfigMap: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl -n kube-system get configmap coredns -o yaml > ``` Then apply the new ConfigMap: ``` kubectl apply -f --context ``` 2. For each region, check that your CoreDNS settings were applied: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl get -n kube-system cm/coredns --export -o yaml --context ``` ### Exclude VPCs from SNAT You will need to tell AWS to exclude your VPCs from [source network address translation (SNAT)](https://docs.aws.amazon.com/eks/latest/userguide/external-snat.html). This ensures that cross-VPC traffic is handled correctly by AWS while still allowing access to the public internet from the pods. Set `AWS_VPC_K8S_CNI_EXCLUDE_SNAT_CIDRS` to recognize the values of your 3 CIDR blocks. Do this for all 3 regions: ``` kubectl set env ds aws-node -n kube-system AWS_VPC_K8S_CNI_EXCLUDE_SNAT_CIDRS="cidr1,cidr2,cidr3" --context ``` Remember that these are the CIDR blocks you chose when [starting your Kubernetes clusters](#step-1-start-kubernetes-clusters). You can also get the IP range of a VPC by opening the [Amazon VPC console](https://console.aws.amazon.com/vpc/) and finding the VPC listed in the section called Your VPCs. > [!NOTE] > > If you plan to run your instances exclusively on private subnets, set the following environment variable instead on each region: \kubectl set env ds aws-node -n kube-system AWS_VPC_K8S_CNI_EXTERNALSNAT=true --context \ [!NOTE] > > The below steps use [`cockroach cert` commands](/docs/v26.4/cockroach-cert) to quickly generate and sign the CockroachDB node and client certificates. Read our [Authentication](/docs/v26.4/authentication#using-digital-certificates-with-cockroachdb) docs to learn about other methods of signing certificates. 1. Create two directories: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ mkdir certs my-safe-directory ``` | Directory | Description | | - | - | | `certs` | You'll generate your CA certificate and all node and client certificates and keys in this directory. | | `my-safe-directory` | You'll generate your CA key in this directory and then reference the key when generating node and client certificates. | 2. Create the CA certificate and key pair: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-ca \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 3. Create a client certificate and key pair for the root user: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach cert create-client \ root \ --certs-dir=certs \ --ca-key=my-safe-directory/ca.key ``` 4. For all 3 regions, upload the client certificate and key to the Kubernetes cluster as a secret. > [!TIP] > > Specify the namespace in which the CockroachDB pods will run. You defined these namespaces after [starting your Kubernetes clusters](#step-1-start-kubernetes-clusters). ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create secret \ generic cockroachdb.client.root \ --from-file=certs \ --context \ --namespace ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create secret \ generic cockroachdb.client.root \ --from-file=certs \ --context \ --namespace ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create secret \ generic cockroachdb.client.root \ --from-file=certs \ --context \ --namespace ``` 1. Create the certificate and key pair for your CockroachDB nodes in one region, substituting ` \ --namespace ``` 3. Repeat the previous 2 steps for your 2 remaining regions. You may need to delete the local `node.crt` and `node.key` in your `certs` directory before generating a new node certificate and key pair. 4. For all 3 regions, check that the secrets were created on the cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get secrets --context ``` ``` NAME TYPE DATA AGE cockroachdb-token-db5wp kubernetes.io/service-account-token 3 1m cockroachdb.client.root Opaque 5 1m cockroachdb.node Opaque 6 1m default-token-65489 kubernetes.io/service-account-token 3 5m ``` ### Create StatefulSets 1. Download and open our [multi-region StatefulSet configuration](https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/cockroachdb-statefulset-secure-eks.yaml). You'll save three versions of this file locally, one for each set of 3 CockroachDB nodes per region. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl -O https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/eks/cockroachdb-statefulset-secure-eks.yaml ``` Look for **TODO** comments in the file. These highlight fields you need to define before deploying your StatefulSet. 2. Fill in the namespace where CockroachDB nodes will run in region 1. ``` namespace: ``` 3. Allocate a memory request and limit to CockroachDB on each pod, using the `resources` object in the CockroachDB `containers` spec. > [!TIP] > > These values should be appropriate for the instances that you have provisioned. Run `kubectl describe nodes` to see the available resources. For example, to allocate 8Gi of memory to CockroachDB in each pod: ``` resources: requests: memory: "8Gi" limits: memory: "8Gi" ``` > [!CAUTION] > > If you do not specify a memory request, no memory will be allocated to CockroachDB. If you do not specify a memory limit, the Kubernetes scheduler will allocate the maximum possible amount. 1. The StatefulSet configuration includes a [`cockroach start`](/docs/v26.4/cockroach-start) command that creates the nodes on the Kubernetes pods. In the `--locality` flag, name `region` after region 1. This can technically be an arbitrary value, but it's simplest to use the CockroachDB namespace in region 1. ``` --locality=region= --context --namespace ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f --context --namespace ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl create -f --context --namespace ``` 5. Run `cockroach init` on one of the pods to complete the node startup process and have them join together as a cluster: ``` kubectl exec \ --context \ --namespace \ -it cockroachdb-0 \ -- /cockroach/cockroach init \ --certs-dir=/cockroach/cockroach-certs ``` ``` Cluster successfully initialized ``` 6. Confirm that cluster initialization has completed successfully in each region. The job should be considered successful and the Kubernetes pods should soon be considered `Ready`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --context --namespace ``` ``` NAMESPACE NAME READY STATUS RESTARTS AGE eu-central-1 cockroachdb-0 1/1 Running 0 12m eu-central-1 cockroachdb-1 1/1 Running 0 12m eu-central-1 cockroachdb-2 1/1 Running 0 12m ``` > [!TIP] > > In each Kubernetes cluster, the StatefulSet configuration sets all CockroachDB nodes to write to `stderr`, so if you ever need access to a pod/node's logs to troubleshoot, use `kubectl logs --context --namespace ` rather than checking the log on the persistent volume. ## Step 4. Use the built-in SQL client 1. Use the `client-secure.yaml` file to launch a pod and keep it running indefinitely, specifying the context of the Kubernetes cluster and namespace of the CockroachDB pods to run it in: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} kubectl create -f https://docs.cockroachlabs.com/files/cockroach/cloud/kubernetes/multiregion/client-secure.yaml --context --namespace ``` ``` pod "cockroachdb-client-secure" created ``` The pod uses the `root` client certificate you [generated earlier](#generate-certificates). Note that this will work from any of the three Kubernetes clusters as long as you use the correct namespace and context combination. 2. Get a shell into the pod and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql), again specifying the namespace and context of the Kubernetes cluster where the pod is running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` ``` # Welcome to the cockroach SQL interface. # All statements must be terminated by a semicolon. # To exit: CTRL + D. # # Server version: CockroachDB CCL v2.0.5 (x86_64-unknown-linux-gnu, built 2018/08/13 17:59:42, go1.10) (same version as client) # Cluster ID: 99346e82-9817-4f62-b79b-fdd5d57f8bda # # Enter \? for a brief introduction. # warning: no current database set. Use SET database = to change, CREATE DATABASE to make a new database. root@cockroachdb-public:26257/> ``` 3. Run some basic [CockroachDB SQL statements](/docs/v26.4/learn-cockroachdb-sql): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE DATABASE bank; ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE TABLE bank.accounts (id INT PRIMARY KEY, balance DECIMAL); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO bank.accounts VALUES (1, 1000.50); ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT * FROM bank.accounts; ``` ``` +----+---------+ | id | balance | +----+---------+ | 1 | 1000.5 | +----+---------+ (1 row) ``` 4. [Create a user with a password](/docs/v26.4/create-user#create-a-user-with-a-password): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > CREATE USER roach WITH PASSWORD 'Q7gc8rEdS'; ``` You will need this username and password to access the DB Console in the next step. 5. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` The pod will continue running indefinitely, so any time you need to reopen the built-in SQL client or run any other [`cockroach` client commands](/docs/v26.4/cockroach-commands) (e.g., `cockroach node`), repeat step 2 using the appropriate command. If you'd prefer to delete the pod and recreate it when needed, run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod cockroachdb-client-secure --context ``` ## Step 5. Access the DB Console To access the cluster's [DB Console](/docs/v26.4/ui-overview): 1. On secure clusters, [certain pages of the DB Console](/docs/v26.4/ui-overview#db-console-access) can only be accessed by `admin` users. Get a shell into the pod with the `cockroach` binary created earlier and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` 2. Assign `roach` to the `admin` role (you only need to do this once): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > GRANT admin TO roach; ``` 3. Exit the SQL shell and pod: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > \q ``` 4. Port-forward from your local machine to a pod in one of your Kubernetes clusters: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl port-forward cockroachdb-0 8080 --context --namespace ``` ``` Forwarding from 127.0.0.1:8080 -> 8080 ``` > [!NOTE] > > The `port-forward` command must be run on the same machine as the web browser in which you want to view the DB Console. If you have been running these commands from a cloud instance or other non-local shell, you will not be able to view the UI without configuring `kubectl` locally and running the above `port-forward` command on your local machine. 1. Go to [https://localhost:8080](https://localhost:8080) and log in with the username and password created in the [Use the built-in SQL client](#step-3-use-the-built-in-sql-client) step. 2. In the UI, check the [**Node List**](/docs/v26.4/ui-cluster-overview-page#node-list) to verify that all nodes are running, open the [**Databases** page](/docs/v26.4/ui-databases-page) to verify that `bank` is listed, and open the [**Network Latency** page](/docs/v26.4/ui-network-latency-page) to see the performance of your CockroachDB cluster across 3 regions. ## Step 6. Simulate datacenter failure One of the major benefits of running a multi-region CockroachDB cluster is that an entire datacenter or region can go down without affecting the availability of the cluster as a whole. To see this in action: 1. Scale down one of the StatefulSets to zero pods, specifying the namespace and context of the Kubernetes cluster where it's running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl scale statefulset cockroachdb --replicas=0 --context --namespace ``` ``` statefulset "cockroachdb" scaled ``` 2. In the DB Console, the **Cluster Overview** will soon show the three nodes from that region as **Suspect**. If you wait for 5 minutes or more, they will be listed as **Dead**. Note that even though there are three dead nodes, the other nodes are all healthy, and any clients using the database in the other regions will continue to work just fine. 3. When you're done verifying that the cluster still fully functions with one of the regions down, you can bring the region back up by running: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl scale statefulset cockroachdb --replicas=3 --context --namespace ``` ``` statefulset "cockroachdb" scaled ``` ## Step 7. Maintain the cluster * [Scale the cluster](#scale-the-cluster) * [Upgrade the cluster](#upgrade-the-cluster) * [Stop the cluster](#stop-the-cluster) ### Scale the cluster Each of your Kubernetes clusters contains 3 instances that can run CockroachDB pods. It's easy to scale a cluster to run more pods. To ensure that you do not have two CockroachDB pods on the same instance (as recommended in our [production best practices](/docs/v26.4/recommended-production-settings)), you need to first add a new instance and then edit your StatefulSet configuration to add another pod. 1. [Resize your Kubernetes cluster.](https://eksctl.io/usage/managing-nodegroups/#scaling) 2. Use the `kubectl scale` command to add a pod to the StatefulSet in the Kubernetes cluster where you want to add a CockroachDB node: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl scale statefulset cockroachdb --replicas=4 --context --namespace ``` ``` statefulset "cockroachdb" scaled ``` 3. Verify that a fourth pod was added successfully: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --context --namespace ``` ``` NAME READY STATUS RESTARTS AGE cockroachdb-0 1/1 Running 0 1h cockroachdb-1 1/1 Running 0 1h cockroachdb-2 1/1 Running 0 7m cockroachdb-3 1/1 Running 0 44s cockroachdb-client-secure 1/1 Running 0 26m ``` ### Upgrade the cluster We strongly recommend that you regularly upgrade your CockroachDB version in order to pick up bug fixes, performance improvements, and new features. The upgrade process on Kubernetes is a [staged update](https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/#staging-an-update) in which the Docker image is applied to the pods one at a time, with each pod being stopped and restarted in turn. This is to ensure that the cluster remains available during the upgrade. 1. Verify that you can upgrade. To upgrade to a new major version, you must first be on a production release of the previous version. The release does not need to be the latest production release of the previous version, but it must be a production [release](/docs/releases/index) and not a testing release (alpha/beta). Therefore, in order to upgrade to v26.4, you must be on a production release of . 1. If you are upgrading to v26.4 from a production release earlier than v26.3, or from a testing release (alpha/beta), first [upgrade to a production release of v26.3](/docs/v26.4/orchestrate-cockroachdb-with-kubernetes-multi-cluster#upgrade-the-cluster). Be sure to complete all the steps. 2. Then return to this page and perform a second upgrade to v26.4. 3. If you are upgrading from any production release of , or from any earlier v26.4 release, you do not have to go through intermediate releases; continue to step 2. 2. Verify the overall health of your cluster using the [DB Console](/docs/v26.4/ui-overview). On the **Overview**: * Under **Node Status**, make sure all nodes that should be live are listed as such. If any nodes are unexpectedly listed as suspect or dead, identify why the nodes are offline and either restart them or decommission them before beginning your upgrade. If there are dead and non-decommissioned nodes in your cluster, it will not be possible to finalize the upgrade (either automatically or manually). * Under **Replication Status**, make sure there are 0 under-replicated and unavailable ranges. Otherwise, performing a rolling upgrade increases the risk that ranges will lose a majority of their replicas and cause cluster unavailability. Therefore, it's important to identify and resolve the cause of range under-replication and/or unavailability before beginning your upgrade. * In the **Node List**: * Make sure all nodes are on the same version. If any nodes are behind, upgrade them to the cluster's current version first, and then start this process over. * Make sure capacity and memory usage are reasonable for each node. Nodes must be able to tolerate some increase in case the new version uses more resources for your workload. Also go to **Metrics > Dashboard: Hardware** and make sure CPU percent is reasonable across the cluster. If there's not enough headroom on any of these metrics, consider [adding nodes](#scale-the-cluster) to your cluster before beginning your upgrade. 3. Review the backward-incompatible changes in v26.4 and deprecated features. If any affect your deployment, make the necessary changes before starting the rolling upgrade to v26.4. 4. Decide how the upgrade will be finalized. By default, after all nodes are running the new version, the upgrade process will be **auto-finalized**. This will enable certain features and performance improvements introduced in v26.4. After finalization, however, it will no longer be possible to perform a downgrade to . In the event of a catastrophic failure or corruption, the only option is to start a new cluster using the old binary and then restore from a [backup](/docs/v26.4/take-full-and-incremental-backups) created prior to the upgrade. For this reason, **we recommend disabling auto-finalization** so you can monitor the stability and performance of the upgraded cluster before finalizing the upgrade, but note that you will need to follow all of the subsequent directions, including the manual finalization in a later step. > [!NOTE] > > Finalization only applies when performing a major version upgrade (for example, from .x to v26.4). Patch version upgrades (for example, within the v26.4.x series) can always be downgraded. 1. Get a shell into the pod with the `cockroach` binary created earlier and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` 2. Set the `cluster.preserve_downgrade_option` [cluster setting](/docs/v26.4/cluster-settings): ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SET CLUSTER SETTING cluster.preserve_downgrade_option = '21.1'; ``` 3. For each Kubernetes cluster, kick off the upgrade process by changing the desired Docker image. To do so, pick the version that you want to upgrade to, then run the following command, replacing "VERSION" with your desired new version and specifying the relevant namespace and "context" name for the Kubernetes cluster: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch statefulset cockroachdb --namespace --context --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"cockroachdb/cockroach:VERSION"}]' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch statefulset cockroachdb --namespace --context --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"cockroachdb/cockroach:VERSION"}]' ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl patch statefulset cockroachdb --namespace --context --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"cockroachdb/cockroach:VERSION"}]' ``` 4. If you then check the status of the pods in each Kubernetes cluster, you should see one of them being restarted: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get pods --selector app=cockroachdb --all-namespaces --context ``` This will continue until all of the pods have restarted and are running the new image. 5. If you disabled auto-finalization earlier, monitor the stability and performance of your cluster until you are comfortable with the upgrade (generally at least a day). If you decide to roll back the upgrade, repeat the rolling restart procedure with the old binary. > [!NOTE] > > This is only possible when performing a major version upgrade (for example, from .x to v26.4). Patch version upgrades (for example, within the v26.4.x series) are auto-finalized. To finalize the upgrade, re-enable auto-finalization: 1. Get a shell into the pod with the `cockroach` binary created earlier and start the CockroachDB [built-in SQL client](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl exec -it cockroachdb-client-secure --context --namespace -- ./cockroach sql --certs-dir=/cockroach-certs --host=cockroachdb-public ``` 2. Re-enable auto-finalization: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > RESET CLUSTER SETTING cluster.preserve_downgrade_option; ``` ### Stop the cluster 1. In each region, delete all of the resources associated with the `cockroachdb` label, including the logs, and remote persistent volumes: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pods,statefulsets,services,persistentvolumeclaims,persistentvolumes,poddisruptionbudget,jobs,rolebinding,clusterrolebinding,role,clusterrole,serviceaccount -l app=cockroachdb --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pods,statefulsets,services,persistentvolumeclaims,persistentvolumes,poddisruptionbudget,jobs,rolebinding,clusterrolebinding,role,clusterrole,serviceaccount -l app=cockroachdb --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pods,statefulsets,services,persistentvolumeclaims,persistentvolumes,poddisruptionbudget,jobs,rolebinding,clusterrolebinding,role,clusterrole,serviceaccount -l app=cockroachdb --context ``` ``` pod "cockroachdb-0" deleted pod "cockroachdb-1" deleted pod "cockroachdb-2" deleted service "cockroachdb" deleted service "cockroachdb-public" deleted persistentvolumeclaim "datadir-cockroachdb-0" deleted persistentvolumeclaim "datadir-cockroachdb-1" deleted persistentvolumeclaim "datadir-cockroachdb-2" deleted poddisruptionbudget.policy "cockroachdb-budget" deleted rolebinding.rbac.authorization.k8s.io "cockroachdb" deleted clusterrolebinding.rbac.authorization.k8s.io "cockroachdb" deleted role.rbac.authorization.k8s.io "cockroachdb" deleted clusterrole.rbac.authorization.k8s.io "cockroachdb" deleted serviceaccount "cockroachdb" deleted ``` 2. Delete the pod created for `cockroach` client commands, if you didn't do so earlier: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete pod cockroachdb-client-secure --context ``` ``` pod "cockroachdb-client-secure" deleted ``` 3. Get the names of the secrets you created on each cluster. These should be identical in all 3 regions: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl get secrets --context ``` ``` NAME TYPE DATA AGE cockroachdb.client.root Opaque 5 1d cockroachdb.node Opaque 6 1d ... ``` 4. Delete the secrets that you created: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete secrets cockroachdb.client.root cockroachdb.node --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete secrets cockroachdb.client.root cockroachdb.node --context ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ kubectl delete secrets cockroachdb.client.root cockroachdb.node --context ``` 5. Stop Kubernetes in each region: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl delete cluster --name cockroachdb1 --region ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl delete cluster --name cockroachdb2 --region ``` ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ eksctl delete cluster --name cockroachdb3 --region ``` 6. Open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) to verify that the stacks were successfully deleted in each region. > [!CAUTION] > > If you stop Kubernetes without first deleting the persistent volumes, they will still exist in your cloud project. ## See also * [Kubernetes Single-Cluster Deployment](/docs/v26.4/deploy-cockroachdb-with-kubernetes) * [Kubernetes Performance Guide](/docs/v26.4/kubernetes-performance) * [Production Checklist](/docs/v26.4/recommended-production-settings) * [Manual Deployment](/docs/v26.4/manual-deployment) * [Orchestrated Deployment](/docs/v26.4/kubernetes-overview) * [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting) * [Performance Tuning](/docs/v26.4/performance-best-practices-overview) * [Local Deployment](/docs/v26.4/start-a-local-cluster) # Override Deployment Templates with the CockroachDB Operator Source: https://docs.cockroachlabs.com/docs/stable/override-templates-cockroachdb-operator The CockroachDB operator provides abstractions that simplify cluster deployment and node initialization: * A default pod specification is used for the CockroachDB Kubernetes pod. * The `values.yaml` configuration maps to a subset of `cockroach start` flags when CockroachDB is initialized. This page describes configuration options that allow advanced users to manually override pod template metadata and `cockroach start` flags as needed for deployment. > [!CAUTION] > > This page describes advanced configurations that override the supported default templates used by the CockroachbDB operator. Cockroach Labs strongly recommends testing these configurations in a non-production environment first. ## Override the default pod The `cockroachdb.crdbCluster.podTemplate` field allows you to override the default pod metadata and specification configured by the CockroachbDB operator. The values in this field are merged with the default pod specification, where settings in `podTemplate` override any values in the default. The `podTemplate` field includes a `containers` field that specifies the container name and image that the template is applied to. By default, this resolves to the `cockroachdb` container name and can be excluded from modifications to the CockroachDB pod template YAML. If needed, you can provide specific images for the `containers` and `initContainers`. For example, the following `podTemplate` configuration specifies a custom init container: ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: podTemplate: # metadata captures the pod metadata for CockroachDB pods. metadata: {} # spec captures the pod specification for CockroachDB pods. spec: # initContainers captures the list of init containers for CockroachDB pods. initContainers: - name : cockroachdb-init image: us-docker.pkg.dev/releases-prod/self-hosted/init-container@sha256:example1234567890abcdefghijklmnopqrstuvwxyz ``` ## Override the default `cockroach start` flags The `cockroachdb.crdbCluster.startFlags` field allows you to customize the [`cockroach start` flags](/docs/v26.4/cockroach-start#flags) used when initializing the CockroachDB cluster. Within this field, you can specify flags to upsert and flags to omit: * Upserted flags are added to the `cockroach start` command, their values overriding any matching flags in the command. * Omitted flags are removed from the `cockroach start` command if they were present. ```yaml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroachdb: crdbCluster: startFlags: # upsert captures a set of flags that are given higher precedence in the start command. upsert: - "--cache=30%" # omit defines a set of flags which will be omitted from the start command. omit: - "--max-sql-memory" ``` # PostgreSQL Compatibility Source: https://docs.cockroachlabs.com/docs/stable/postgresql-compatibility CockroachDB supports the [PostgreSQL wire protocol](https://www.postgresql.org/docs/current/protocol.html) and the majority of PostgreSQL syntax. This means that existing applications built on PostgreSQL can often be migrated to CockroachDB without changing application code. CockroachDB is compatible with version 3.0 of the PostgreSQL wire protocol (pgwire) and works with the majority of PostgreSQL database tools such as [DBeaver](/docs/v26.4/dbeaver), [Intellij](/docs/v26.4/intellij-idea), and so on. Consult this link for a full list of supported [third-party database tools](/docs/v26.4/third-party-database-tools). CockroachDB also works with most PostgreSQL drivers and ORMs. CockroachDB reports PostgreSQL version 18 in the `server_version` and `server_version_num` [session variables](/docs/v26.4/session-variables), and the tables in the [`pg_catalog`](/docs/v26.4/pg-catalog) schema are aligned with the PostgreSQL 18 system catalogs. When a client connects, CockroachDB sends all the startup status parameters that drivers expect from PostgreSQL 18. These parameters include `search_path`, `default_transaction_read_only`, `in_hot_standby`, and `scram_iterations`. Because CockroachDB has no primary/standby distinction, drivers that read `in_hot_standby` to detect standby servers always receive `off`. However, CockroachDB does not support some of the PostgreSQL features or behaves differently from PostgreSQL because not all features can be easily implemented in a distributed system. This page documents the known list of differences between PostgreSQL and CockroachDB for identical input. That is, a SQL statement of the type listed here will behave differently than in PostgreSQL. Porting an existing application to CockroachDB will require changing these expressions. > [!NOTE] > > This document does not discuss strategies for porting applications that use SQL features CockroachDB does not support. ## Unsupported features The following PostgreSQL features are not supported in CockroachDB v26.4: ### PostgreSQL range types CockroachDB does not support PostgreSQL range types. ### Other unsupported features * Events. * Drop primary key. > [!NOTE] > > Each table must have a primary key associated with it. You can [drop and add a primary key constraint within a single transaction](/docs/v26.4/alter-table#drop-and-add-a-primary-key-constraint). * XML functions. * Column-level privileges. * XA syntax. * Creating a database from a template. * [Dropping a single partition from a table](/docs/v26.4/partitioning#known-limitations). * Foreign data wrappers. * Session-scoped advisory lock functions. Transaction-scoped advisory locks are supported. Refer to [Advisory locks](/docs/v26.4/postgresql-compatibility#advisory-locks). ## Partially supported features The following PostgreSQL features are partially supported in CockroachDB v26.4. ### Export a CockroachDB schema with `pg_dump` CockroachDB supports using PostgreSQL 18's `pg_dump` command to export the schema definitions from a CockroachDB database. Use the plain-text dump format to recreate the schema in another CockroachDB database or to generate PostgreSQL-oriented schema definitions. For operational backups and disaster recovery, use CockroachDB [`BACKUP` and `RESTORE`](backup-and-restore-overview). Unlike `pg_dump`, CockroachDB backup and restore jobs provide distributed execution, job management, and CockroachDB-specific recovery capabilities. #### Before you begin * Install the [PostgreSQL 18 client tools](https://www.postgresql.org/docs/18/app-pgdump.html). The examples on this page use PostgreSQL 18.3. * Use a [source user](/docs/v26.4/security-reference/authorization#sql-users) that can access every schema object to export. * Before restoring a schema, create an empty target database. #### Choose a compatibility mode The [`pg_dump_compatibility` session variable](set-vars#supported-variables) controls the metadata and syntax that CockroachDB presents to `pg_dump`. | Value | Behavior | Use when | | - | - | - | | `off` | Disables dump-specific catalog and syntax adjustments. This is the default for other clients. | You do not want dump compatibility behavior. | | `cockroachdb` | Applies PostgreSQL catalog and OID compatibility fixups, hides CockroachDB-internal objects, and preserves CockroachDB-specific syntax. | The schema will be restored into CockroachDB. | | `postgres` | Applies the catalog and OID fixups, hides CockroachDB-internal objects, and suppresses CockroachDB-specific storage parameters and locality syntax. | The schema definitions must use PostgreSQL-oriented syntax. | A client with an exact, case-sensitive `application_name` of `pg_dump`, `pg_restore`, or `pg_dumpall` automatically uses `pg_dump_compatibility=cockroachdb`. CockroachDB emits a `NOTICE` when it selects this mode. An explicit value in the connection string, including `off` or `postgres`, overrides automatic selection. Automatic mode selection for `pg_restore` and `pg_dumpall` does not indicate end-to-end support for those tools. Refer to [Known limitations](#known-limitations-for-postgresql-dump-tools). #### Export and restore a CockroachDB schema For a CockroachDB-target schema, allow CockroachDB to select `pg_dump_compatibility=cockroachdb` automatically. To dump the `bank` database schema in plain format, run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} pg_dump \ --dbname="$SOURCE_URL" \ --schema-only \ --format=plain \ --no-owner \ --no-privileges \ --file=bank-schema.sql ``` `$SOURCE_URL` is the [connection URL](/docs/v26.4/connection-parameters#connect-using-a-url) for the source CockroachDB database. `pg_dump` automatically uses `pg_dump_compatibility=cockroachdb`, so CockroachDB-specific definitions remain in `bank-schema.sql`. To restore the schema into an empty `bank` database on another CockroachDB cluster with `psql`, run: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} psql \ --dbname="$TARGET_URL" \ --set=ON_ERROR_STOP=on \ --file=bank-schema.sql ``` `$TARGET_URL` is the [connection URL](/docs/v26.4/connection-parameters#connect-using-a-url) for the empty target CockroachDB database. As an alternative to `psql`, restore the plain script with the [CockroachDB SQL shell](/docs/v26.4/cockroach-sql): ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --url="$TARGET_URL" --file=bank-schema.sql ``` PostgreSQL 18 `pg_dump` scripts use the `\restrict` and `\unrestrict` metacommands to prevent other backslash commands in a plain-text dump from running on the client. The [CockroachDB SQL shell](/docs/v26.4/cockroach-sql) supports these commands and preserves restricted mode across files included with `\i` or `\ir`. #### Generate PostgreSQL-oriented schema definitions To generate PostgreSQL-oriented schema definitions, explicitly set `pg_dump_compatibility=postgres` in the source connection string. In a [connection URL](/docs/v26.4/connection-parameters#connect-using-a-url), pass the setting with the URL-encoded `options` parameter: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} pg_dump \ --dbname="postgresql://{user}:{password}@{host}:26257/bank?sslmode=verify-full&options=-c%20pg_dump_compatibility%3Dpostgres" \ --schema-only \ --format=plain \ --no-owner \ --no-privileges \ --file=bank-schema-for-postgres.sql ``` Replace `{user}`, `{password}`, and `{host}` with the source CockroachDB connection parameters. The `postgres` mode removes CockroachDB-specific syntax that the compatibility layer recognizes. It does not translate every CockroachDB type, expression, or feature to a PostgreSQL equivalent. Review the script and test the restore on the target PostgreSQL version. #### Known limitations for PostgreSQL dump tools * Only schema-only dumps in plain format are supported. Data dumps, non-plain archive formats, `pg_restore`, and `pg_dumpall` are not supported. * `pg_dump` dumps one database and does not include cluster-wide objects such as [users](/docs/v26.4/security-reference/authorization#sql-users) and [roles](/docs/v26.4/security-reference/authorization#roles). * Unvalidated domain [`CHECK` constraints](/docs/v26.4/check) added with `ALTER DOMAIN ... ADD CONSTRAINT ... NOT VALID` might not be included in the dump. Verify that these constraints are present before restoring it. * CockroachDB stores a sequence value without PostgreSQL's separate `is_called` state. CockroachDB-to-CockroachDB round trips preserve the stored value. If `setval(sequence, value, false)` uses a value other than the sequence start value, `pg_dump` reports `(value - increment, true)` rather than `(value, false)`. * PostgreSQL-oriented output might require manual changes for CockroachDB-specific objects and for the [unsupported](#unsupported-features) or [partially supported](#partially-supported-features) features described on this page. ### Multiple active portals CockroachDB v26.4 supports pgwire's multiple active portals as a [preview feature](/docs/releases/cockroachdb-feature-availability). The feature is off by default, and can be enabled by setting the [session variable `multiple_active_portals_enabled`](/docs/v26.4/set-vars#multiple-active-portals-enabled) to `true`. When set to `true`, multiple portals can be open at the same time, with their execution interleaved with each other. In other words, these portals can be paused. This feature has the following limitations: * Only read-only [`SELECT` queries](/docs/v26.4/selection-queries) without [subqueries](/docs/v26.4/subqueries) are supported. * Postqueries (which are how CockroachDB executes [foreign key checks](/docs/v26.4/foreign-key), for example) are not supported. * [Distributed SQL execution](/docs/v26.4/architecture/sql-layer#distsql) is not supported for multiple active portals; instead queries execute on the [gateway node](/docs/v26.4/architecture/life-of-a-distributed-transaction#gateway) only. * Only the latest execution of a statement from a pausable portal is recorded by the [trace infrastructure](/docs/v26.4/show-trace). In addition to the known issues, additional performance testing is needed. ### Advisory locks CockroachDB supports transaction-scoped advisory locks: `pg_advisory_xact_lock`, `pg_advisory_xact_lock_shared`, `pg_try_advisory_xact_lock`, and `pg_try_advisory_xact_lock_shared`. Each function takes either a single `INT` key or two `INT4` keys. A lock is tied to the transaction that acquires it and is released when the transaction commits or rolls back. For function descriptions, refer to [compatibility functions](/docs/v26.4/functions-and-operators#compatibility-functions). Transaction-scoped advisory locks behave as follows: * The lock keyspace is scoped to the current database, matching PostgreSQL: the same key refers to different locks in different databases. * `pg_advisory_xact_lock` and `pg_advisory_xact_lock_shared` wait until the lock is available. If the [`lock_timeout` session variable](/docs/v26.4/set-vars#lock-timeout) is set, an acquisition that waits longer than the timeout fails with the error `canceling statement due to lock timeout`. * `pg_try_advisory_xact_lock` and `pg_try_advisory_xact_lock_shared` do not wait. They return `false` if the lock is not immediately available. * If transactions deadlock on advisory locks, CockroachDB fails one of the transactions with a [transaction retry error](/docs/v26.4/transaction-retry-error-reference). As in PostgreSQL, the failed transaction must be retried by the client. * Granted and waiting advisory locks are reported in the [`pg_locks`](/docs/v26.4/pg-catalog) view. In a cluster that is upgrading to v26.3, the advisory lock functions return an error until the upgrade is finalized. Session-scoped advisory locks are not supported. The session-scoped functions fall into two groups: * `pg_advisory_lock`, `pg_advisory_lock_shared`, and `pg_try_advisory_lock_shared` are not defined. Calling them returns an error. * `pg_try_advisory_lock`, `pg_advisory_unlock`, `pg_advisory_unlock_shared`, and `pg_advisory_unlock_all` are defined for compatibility, but do not acquire or release locks. They silently succeed without any effect: `pg_try_advisory_lock`, `pg_advisory_unlock`, and `pg_advisory_unlock_shared` always return `true`, and `pg_advisory_unlock_all` performs no action. ## Features that differ from PostgreSQL Note, some of the differences below only apply to rare inputs, and so no change will be needed, even if the listed feature is being used. In these cases, it is safe to ignore the porting instructions. ### Overflow of `float` In PostgreSQL, the `float` type returns an error when it overflows or an expression would return Infinity: ``` postgres=# select 1e300::float * 1e10::float; ERROR: value out of range: overflow postgres=# select pow(0::float, -1::float); ERROR: zero raised to a negative power is undefined ``` In CockroachDB, these expressions instead return Infinity: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT 1e300::float * 1e10::float; ``` ``` ?column? ------------ +Inf (1 row) ``` ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT pow(0::float, -1::float); ``` ``` pow -------- +Inf (1 row) ``` ### Precedence of unary `~` In PostgreSQL, the unary `~` (bitwise not) operator has a low precedence. For example, the following query is parsed as `~ (1 + 2)` because `~` has a lower precedence than `+`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT ~1 + 2; ``` ``` ?column? ------------ 0 (1 row) ``` In CockroachDB, unary `~` has the same (high) precedence as unary `-`, so the above expression will be parsed as `(~1) + 2`. **Porting instructions:** Manually add parentheses around expressions that depend on the PostgreSQL behavior. ### Precedence of bitwise operators In PostgreSQL, the operators `|` (bitwise OR), `#` (bitwise XOR), and `&` (bitwise AND) all have the same precedence. In CockroachDB, the precedence from highest to lowest is: `&`, `#`, `|`. **Porting instructions:** Manually add parentheses around expressions that depend on the PostgreSQL behavior. ### Integer division In PostgreSQL, division of integers results in an integer. For example, the following query returns `1`, since the `1 / 2` is truncated to `0`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT 1 + 1 / 2; ``` ``` ?column? ------------ 1.5 (1 row) ``` In CockroachDB, integer division results in a `decimal`. CockroachDB instead provides the `//` operator to perform floor division. **Porting instructions:** Change `/` to `//` in integer division where the result must be an integer. ### Shift argument modulo In PostgreSQL, the shift operators (`<<`, `>>`) sometimes modulo their second argument to the bit size of the underlying type. For example, the following query results in a `1` because the int type is 32 bits, and `32 % 32` is `0`, so this is the equivalent of `1 << 0`: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT 1::int << 32; ``` ``` ?column? -------------- 4294967296 (1 row) ``` In CockroachDB, no such modulo is performed. **Porting instructions:** Manually add a modulo to the second argument. Also note that CockroachDB's [`INT`](/docs/v26.4/int) type is always 64 bits. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SELECT 1::int << (x % 64); ``` ### Locking and `FOR UPDATE` CockroachDB supports the `SELECT FOR UPDATE` statement, which is used to order transactions by controlling concurrent access to one or more rows of a table. For more information, see [`SELECT FOR UPDATE`](/docs/v26.4/select-for-update). ### `CHECK` constraint validation for `INSERT ON CONFLICT` CockroachDB validates [`CHECK`](/docs/v26.4/check) constraints on the results of [`INSERT ON CONFLICT`](/docs/v26.4/insert#on-conflict-clause) statements, preventing new or changed rows from violating the constraint. Unlike PostgreSQL, CockroachDB does not also validate `CHECK` constraints on the input rows of `INSERT ON CONFLICT` statements. If this difference matters to your client, you can `INSERT ON CONFLICT` from a `SELECT` statement and check the inserted value as part of the `SELECT`. For example, instead of defining `CHECK (x > 0)` on `t.x` and using `INSERT INTO t(x) VALUES (3) ON CONFLICT (x) DO UPDATE SET x = excluded.x`, you could do the following: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > INSERT INTO t (x) SELECT if (x <= 0, crdb_internal.force_error('23514', 'check constraint violated'), x) FROM (values (3)) AS v(x) ON CONFLICT (x) DO UPDATE SET x = excluded.x; ``` An `x` value less than `1` would result in the following error: ``` pq: check constraint violated ``` ### Column name from an outer column inside a subquery CockroachDB returns the column name from an outer column inside a subquery as `?column?`, unlike PostgreSQL. For example: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} > SELECT (SELECT t.*) FROM (VALUES (1)) t(x); ``` CockroachDB: ``` ?column? ------------ 1 ``` PostgreSQL: ``` x --- 1 ``` ### `LIKE` patterns that end with an escape character In CockroachDB, a [`LIKE` or `ILIKE`](/docs/v26.4/scalar-expressions#string-pattern-matching) pattern that ends with an unpaired escape character always returns an error. PostgreSQL also returns an error when the input string has more characters left to match at that point; when there are no characters left, it returns `false`. For example, `SELECT 'ABC' LIKE 'ABC!' ESCAPE '!';` returns an error in CockroachDB and `false` in PostgreSQL. The default escape character is the backslash (`\`). ### SQL compatibility Click the following link to find a full list of [CockroachDB supported SQL Features](/docs/v26.4/sql-feature-support). # Prometheus Endpoint Source: https://docs.cockroachlabs.com/docs/stable/prometheus-endpoint Each node in a CockroachDB cluster exports granular time-series metrics to two available Prometheus-compatible endpoints: * [`http:// [!NOTE] > > In addition to using the exported time-series data to monitor a cluster through an external system, you can write alerting rules to ensure prompt notification of critical events or issues requiring intervention or investigation. Refer to [Essential Alerts](/docs/v26.4/essential-alerts-self-hosted) for more details. Even if you rely on external tools for storing and visualizing your cluster's time-series metrics, CockroachDB continues to store time-series metrics for its [DB Console Metrics dashboards](/docs/v26.4/monitoring-and-alerting#metrics-dashboards). These stored time-series metrics may be used to generate a [tsdump](/docs/v26.4/cockroach-debug-tsdump), which may be critical during investigations with Cockroach Labs support. ## `_status/vars` To access the `_status/vars` Prometheus endpoint of a cluster running on `localhost:8080`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl http://localhost:8080/_status/vars ``` The output will be similar to the following. Note that the metric names are unique for `sql_*_count*`. ``` # HELP sys_cgocalls Total number of cgo calls # TYPE sys_cgocalls counter sys_cgocalls{node_id="1",tenant="demoapp"} 13737 # HELP sys_cpu_sys_percent Current system cpu percentage consumed by the CRDB process # TYPE sys_cpu_sys_percent gauge sys_cpu_sys_percent{node_id="1",tenant="demoapp"} 0.0021986027879282717 ... # HELP sql_select_count_internal Number of SQL SELECT statements successfully executed (internal queries) # TYPE sql_select_count_internal counter sql_select_count_internal{node_id="1",tenant="demoapp"} 2115 ... # HELP sql_delete_count Number of SQL DELETE statements successfully executed # TYPE sql_delete_count counter sql_delete_count{node_id="1",tenant="demoapp"} 0 ... # HELP sql_delete_count_internal Number of SQL DELETE statements successfully executed (internal queries) # TYPE sql_delete_count_internal counter sql_delete_count_internal{node_id="1",tenant="demoapp"} 996 ... # HELP sql_select_count Number of SQL SELECT statements successfully executed # TYPE sql_select_count counter sql_select_count{node_id="1",tenant="demoapp"} 9 ... # HELP sql_insert_count_internal Number of SQL INSERT statements successfully executed (internal queries) # TYPE sql_insert_count_internal counter sql_insert_count_internal{node_id="1",tenant="demoapp"} 1201 ... # HELP sql_update_count Number of SQL UPDATE statements successfully executed # TYPE sql_update_count counter sql_update_count{node_id="1",tenant="demoapp"} 0 ... # HELP sql_update_count_internal Number of SQL UPDATE statements successfully executed (internal queries) # TYPE sql_update_count_internal counter sql_update_count_internal{node_id="1",tenant="demoapp"} 1907 ... # HELP sql_insert_count Number of SQL INSERT statements successfully executed # TYPE sql_insert_count counter sql_insert_count{node_id="1",tenant="system"} 12 sql_insert_count{node_id="1",tenant="demoapp"} 15 ... ``` ## `metrics` > [!NOTE] > > **This feature is in [preview](/docs/releases/cockroachdb-feature-availability)** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com). The `metrics` Prometheus endpoint is commonly used and is the default in Prometheus configurations. To access the `metrics` Prometheus endpoint of a cluster running on `localhost:8080`: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ curl http://localhost:8080/metrics ``` The output will be similar to the following. Note that there is one metric name for `sql_count`, with static labels for `query_type` (with values of `insert`, `select`, `update`, and `delete`) and `query_internal` (with value of `true`). ``` # HELP sys_cgocalls Total number of cgo calls # TYPE sys_cgocalls counter sys_cgocalls{node_id="1",tenant="demoapp"} 13737 # HELP sys_cpu_sys_percent Current system cpu percentage consumed by the CRDB process # TYPE sys_cpu_sys_percent gauge sys_cpu_sys_percent{node_id="1",tenant="demoapp"} 0.0021986027879282717 ... # HELP sql_count Number of SQL INSERT statements successfully executed (internal queries) # TYPE sql_count counter sql_count{node_id="1",tenant="demoapp",query_type="insert",query_internal="true"} 1281 sql_count{node_id="1",tenant="demoapp",query_type="delete"} 0 sql_count{node_id="1",tenant="demoapp",query_type="update"} 0 sql_count{node_id="1",tenant="demoapp",query_type="select",query_internal="true"} 2280 sql_count{node_id="1",tenant="demoapp",query_type="select"} 9 sql_count{node_id="1",tenant="demoapp",query_type="insert"} 15 sql_count{node_id="1",tenant="demoapp",query_type="update",query_internal="true"} 2102 sql_count{node_id="1",tenant="demoapp",query_type="delete",query_internal="true"} 1067 ... ``` ### Static labels One common use of static labels is to allow segmentation of a metric across various facets for later querying and aggregation. For example, rather than emitting separate metrics for `INSERT`, `SELECT`, `UPDATE`, and `DELETE` statements, the single metric `sql_count` uses the `query_type` label to distinguish between these operations. This enables operators to easily aggregate across query types (e.g., summing a metric for all SQL operations) or filter for a specific type using the appropriate value for the `query_type` label. The following tables contrast unlabeled metrics from the `_status/vars` endpoint with their labeled counterparts from the `metrics` endpoint: | Unlabeled metrics from the `_status/vars` endpoint | Labeled metrics from the `metrics` endpoint | | - | - | | `sql_insert_count` | `sql_count{query_type="insert"}` | | `sql_select_count` | `sql_count{query_type="select"}` | | `sql_update_count` | `sql_count{query_type="update"}` | | `sql_delete_count` | `sql_count{query_type="delete"}` | At metrics query time, labels provide a more seamless user experience: | Unlabeled sum query from the `_status/vars` endpoint | Labeled sum query from the `metrics` endpoint | | - | - | | `sum(sql_insert_count, sql_delete_count, sql_select_count)` | `sum(sql_count)` | | This query must be updated if new types are added, as each will have a unique metric name. | This query is resilient to new type additions. | | Related metrics can be found via autocomplete in a third-party tool, but the results may be ambiguous. | All label values can be found through a third-party query engine and used to easily construct a graph with individual lines for each label value. | In other cases, label values can represent distinct categories not intended for aggregation. For example, certificate expiration metrics differ only by the specific certificate type they represent. Operators are unlikely to sum or average these, but may still want to display them side by side on a dashboard for visibility. In this case, a single metric name like `security_certificate_expiration` is reused, with the certificate type expressed as a label. The `metrics` endpoint returns output similar to the following: ``` # HELP security_certificate_expiration Expiration for the CA certificate # TYPE security_certificate_expiration gauge security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="ca"} 1.998766953e+09 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="ca-client-tenant"} 0 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="node-client"} 0 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="client-tenant"} 0 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="ui"} 0 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="client"} 1.840654953e+09 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="client-ca"} 0 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="ui-ca"} 0 security_certificate_expiration{node_id="1",tenant="demoapp",certificate_type="node"} 1.840654953e+09 ``` This approach avoids a proliferation of metric names and allows third-party tools to display each certificate’s expiration as a separate line in a single graph or table. ## See also * [Monitor CockroachDB with Prometheus](/docs/v26.4/monitor-cockroachdb-with-prometheus) * [Third-party Monitoring Integrations](/docs/v26.4/third-party-monitoring-tools) * [Essential Metrics](/docs/v26.4/essential-metrics-self-hosted) * [Essential Alerts](/docs/v26.4/essential-alerts-self-hosted) # Production Checklist Source: https://docs.cockroachlabs.com/docs/stable/recommended-production-settings This page provides important recommendations for production deployments of CockroachDB. ## Topology When planning your deployment, it's important to carefully review and choose the [topology patterns](/docs/v26.4/topology-patterns) that best meet your latency and resiliency requirements. This is especially crucial for multi-region deployments. Also keep in mind some basic topology recommendations: * Do not run multiple node processes on the same VM or machine. This defeats CockroachDB's replication and causes the system to be a single point of failure. Instead, start each node on a separate VM or machine. * To start a node with multiple disks or SSDs, provide a separate `--store` flag for each disk when starting the `cockroach` process on the node. For more details about stores, see [Start a Node](/docs/v26.4/cockroach-start#store). > [!CAUTION] > > If you start a node with multiple `--store` flags, it is not possible to scale back down to only using a single store on the node. Instead, you must decommission the node and start a new node with the updated `--store`. * When starting each node, use the [`--locality`](/docs/v26.4/cockroach-start#locality) flag to describe the node's location, for example, `--locality=region=west,zone=us-west-1`. The key-value pairs should be ordered from most to least inclusive, and the keys and order of key-value pairs must be the same on all nodes. * When deploying in a single availability zone: * To be able to tolerate the failure of any 1 node, use at least 3 nodes with the [`default` 3-way replication factor](/docs/v26.4/configure-replication-zones#view-the-default-replication-zone). In this case, if 1 node fails, each range retains 2 of its 3 replicas, a majority. * To be able to tolerate 2 simultaneous node failures, use at least 5 nodes and [increase the `default` replication factor for user data](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) to 5. The replication factor for [important internal data](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-system-range) is 5 by default, so no adjustments are needed for internal data. In this case, if 2 nodes fail at the same time, each range retains 3 of its 5 replicas, a majority. * When deploying across multiple availability zones: * To be able to tolerate the failure of 1 entire AZ in a region, use at least 3 AZs per region and set `--locality` on each node to spread data evenly across regions and AZs. In this case, if 1 AZ goes offline, the 2 remaining AZs retain a majority of replicas. * To ensure that ranges are split evenly across nodes, use the same number of nodes in each AZ. This is to avoid overloading any nodes with excessive resource consumption. * When deploying across multiple regions: * To be able to tolerate the failure of 1 entire region, use at least 3 regions. For optimal cluster performance, Cockroach Labs recommends that all nodes use the same hardware and operating system. ## Software We recommend running a [glibc](https://www.gnu.org/software/libc/)-based Linux distribution and Linux kernel version from the last 5 years, such as [Ubuntu](https://ubuntu.com/), [Red Hat Enterprise Linux (RHEL)](https://www.redhat.com/technologies/linux-platforms/enterprise-linux), [CentOS](https://www.centos.org/), or [Container-Optimized OS](https://cloud.google.com/container-optimized-os/docs). We have observed increased memory usage in rare cases due to [transparent huge pages (THP)](https://www.kernel.org/doc/html/latest/admin-guide/mm/transhuge.html) being enabled (i.e., set to `always`). New deployments should configure THP with the `madvise` option. Existing deployments that have THP enabled using the `always` option should change it to `madvise` unless they are currently running with a comfortable memory usage margin. The method for permanently changing the THP setting across reboots depends on the operating system. For Red Hat Enterprise Linux, refer to the [Red Hat documentation](https://access.redhat.com/solutions/46111). ## Hardware > [!NOTE] > > In our sizing and production guidance, 1 vCPU is considered equivalent to 1 core in the underlying hardware platform. ### Sizing The size of your cluster corresponds to its total number of vCPUs. This number depends holistically on your application requirements: total storage capacity, SQL workload response time, SQL [workload concurrency](#connection-pooling), and database service availability. Working from your total vCPU count, you should then decide how many vCPUs to allocate to each machine. The larger the nodes (i.e., the more vCPUs on the machine), the fewer nodes will be in your cluster. Carefully consider the following tradeoffs: * A **smaller number of larger nodes** emphasizes cluster stability. * Larger nodes tolerate [hotspots](/docs/v26.4/understand-hotspots) more effectively than smaller nodes. * Queries operating on large data sets may strain network transfers if the data is spread widely over many smaller nodes. Having fewer and larger nodes enables more predictable workload performance. * A cluster with fewer nodes may be easier to operate and maintain. * A **larger number of smaller nodes** emphasizes resiliency across [failure scenarios](/docs/v26.4/disaster-recovery-planning). * The loss of a small node during failure or routine maintenance has a lesser impact on workload response time and concurrency. * Having more and smaller nodes allows [backup and restore jobs](/docs/v26.4/take-and-restore-encrypted-backups) to complete more quickly, since these jobs run in parallel and less data is hosted on each individual node. * Recovery from a failed node is faster when data is spread across more nodes. A smaller node will also take a shorter time to rebalance to a steady state. In general, distribute your total vCPUs into the **largest possible nodes and smallest possible cluster** that meets your fault tolerance goals. * For cluster stability, Cockroach Labs recommends a *minimum* of **8 vCPUs**, and strongly recommends no fewer than **4 vCPUs** per node. In a cluster with too few CPU resources, foreground client workloads will compete with the cluster's background maintenance tasks. For more information, see [capacity planning issues](/docs/v26.4/cluster-setup-troubleshooting#capacity-planning-issues). > [!NOTE] > > Clusters deployed in CockroachDB Cloud can be created with a minimum of 2 vCPUs per node on AWS and GCP or 4 vCPUs per node on Azure. * Avoid "burstable" or "shared-core" virtual machines that limit the load on CPU resources. * Cockroach Labs does not extensively test clusters with more than **64 vCPUs** per node. This is the recommended *maximum* threshold. * CockroachDB should only run on single-NUMA instances. Running a CockroachDB process across NUMA nodes is not recommended and can heavily impact performance. For more information on how CockroachDB interfaces with NUMA, read the [Linux deployment limitations](/docs/v26.4/install-cockroachdb-linux#numa). ### Basic hardware recommendations After you [size your cluster](#sizing), you can determine the amount of RAM, storage capacity, and disk I/O from the number of vCPUs. This hardware guidance is meant to be platform agnostic and can apply to bare-metal, containerized, and orchestrated deployments. Also see our [cloud-specific](#cloud-specific-recommendations) recommendations. | Value | Recommendation | Reference | | - | - | - | | RAM per vCPU | 4 GiB | [Memory](#memory) | | Capacity per vCPU | | [Storage](#storage) | | IOPS per vCPU | 500 | [Disk I/O](#disk-i/o) | | MB/s per vCPU | 30 | [Disk I/O](#disk-i/o) | Before deploying to production, test and tune your hardware setup for your application workload. For example, read-heavy and write-heavy workloads will place different emphases on [CPU](#sizing), [RAM](#memory), [storage](#storage), [I/O](#disk-i/o), and [network](#networking) capacity. #### Memory Provision at least **4 GiB of RAM per vCPU** for consistency across a variety of workload complexities. The minimum acceptable ratio is 2 GiB of RAM per vCPU, which is only suitable for testing. > [!NOTE] > > The benefits to having more RAM decrease as the [number of vCPUs](#sizing) increases. * To optimize for the support of large numbers of tables, increase the amount of RAM. For more information, see [Quantity of tables and other schema objects](/docs/v26.4/schema-design-overview#quantity-of-tables-and-other-schema-objects). Supporting a large number of rows is a matter of [Storage](#storage). * To ensure consistent SQL performance, make sure all nodes have a uniform configuration. * Disable Linux memory swapping. Over-allocating memory on production machines can lead to unexpected performance issues when pages have to be read back into memory. * To help guard against [out-of-memory (OOM) crashes](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash), consider tuning the cache and SQL memory for cluster nodes. Refer to the section [Cache and SQL memory size](#cache-and-sql-memory-size). * Monitor [CPU](/docs/v26.4/common-issues-to-monitor#cpu-usage) and [memory](/docs/v26.4/common-issues-to-monitor#database-memory-usage) usage. Ensure that they remain within acceptable limits. > [!NOTE] > > Under-provisioning RAM results in reduced performance (due to reduced caching and increased spilling to disk), and in some cases can cause [OOM crashes](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash). For more information, see [memory issues](/docs/v26.4/cluster-setup-troubleshooting#memory-issues). #### Storage We recommend provisioning volumes with **320 GiB per vCPU**. It's fine to have less storage per vCPU if your workload does not have significant capacity needs. * The maximum recommended storage capacity per node is 10 TiB, regardless of the number of vCPUs. * Use dedicated volumes for the CockroachDB store. Do not share the store volume with any other I/O activity. * Determine where CockroachDB log files will be stored: either on the same volume as the main data store or on a separate volume from the main data store. Refer to Storage considerations for file sinks in Logging Best Practices. * The recommended Linux filesystems are [ext4](https://ext4.wiki.kernel.org/index.php/Main_Page) and [XFS](https://xfs.wiki.kernel.org/). * Always keep some of your disk capacity free on production. Doing so accommodates fluctuations in routine database operations and supports continuous data growth. * [Monitor your storage utilization](/docs/v26.4/common-issues-to-monitor#storage-capacity) and rate of growth, and take action to add capacity well before you hit the limit. * CockroachDB will [automatically provision an emergency ballast file](/docs/v26.4/cluster-setup-troubleshooting#automatic-ballast-files) at [node startup](/docs/v26.4/cockroach-start#flags-max-offset). In the unlikely case that a node runs out of disk space and shuts down, you can delete the ballast file to free up enough space to be able to restart the node. * Use [zone configs](/docs/v26.4/configure-replication-zones) to increase the replication factor from 3 (the default) to 5 (across at least 5 nodes). This is especially recommended if you are using local disks rather than a cloud provider's network-attached disks that are often replicated under the hood, because local disks have a greater risk of failure. You can do this for the [entire cluster](/docs/v26.4/configure-replication-zones#edit-the-default-replication-zone) or for specific [databases](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-database), [tables](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-table), or [rows](/docs/v26.4/configure-replication-zones#create-a-replication-zone-for-a-partition). * Considerations for on-premises storage infrastructure: * **Distributed file systems** such as CephFS and GlusterFS should not be used for CockroachDB store volumes. CockroachDB already handles [data distribution](/docs/v26.4/architecture/distribution-layer), [replication](/docs/v26.4/architecture/replication-layer), and fault tolerance using [Raft](/docs/v26.4/architecture/replication-layer#raft). Adding a distributed file system underneath creates a second, uncoordinated layer that can cause duplicate replication, higher and more variable latency, and more complex failures. * **NAS or other storage that presents a filesystem interface over the network** should also not be used for CockroachDB store volumes. Examples include NFS, SMB/CIFS, and Amazon EFS mounted as a filesystem. * **SAN-backed storage** can be used when it presents a block device to the operating system that is formatted with a recommended Linux filesystem such as `ext4` or `xfs`. In that case, it is closer to cloud network-attached block storage than to a distributed file system. Be aware that the additional layers in I/O could break `fsync()` fidelity and lead to undesired behavior. > [!NOTE] > > Under-provisioning storage leads to node crashes when the disks fill up. Once this has happened, it is difficult to recover from. To prevent your disks from filling up, provision enough storage for your workload, monitor your disk usage, and use a [ballast file](/docs/v26.4/cluster-setup-troubleshooting#automatic-ballast-files). For more information, see [capacity planning issues](/docs/v26.4/cluster-setup-troubleshooting#capacity-planning-issues) and [storage issues](/docs/v26.4/cluster-setup-troubleshooting#storage-issues). For instructions on how to free up disk space as quickly as possible after dropping a table, see [How can I free up disk space that was used by a dropped table?](/docs/v26.4/operational-faqs#how-can-i-free-up-disk-space-when-dropping-a-table) ##### Disk I/O Disks must be able to achieve **500 IOPS and 30 MB/s per vCPU**. * [Monitor IOPS](/docs/v26.4/common-issues-to-monitor#disk-iops) using the DB Console and `iostat`. Ensure that they remain within acceptable values. * Use [sysbench](https://github.com/akopytov/sysbench) to benchmark IOPS on your cluster. If IOPS decrease, add more nodes to your cluster to increase IOPS. * Do not use LVM in the I/O path. Dynamically resizing CockroachDB store volumes can result in significant performance degradation. Using LVM snapshots in lieu of CockroachDB backup and restore is also not supported. Use multiple stores per node instead. > [!NOTE] > > Disk I/O especially affects [performance on write-heavy workloads](/docs/v26.4/architecture/reads-and-writes-overview). For more information, see [capacity planning issues](/docs/v26.4/cluster-setup-troubleshooting#capacity-planning-issues). ##### Node density testing configuration In a narrowly-scoped test, we were able to successfully store 4.32 TiB of logical data per node. The results of this test may not be applicable to your specific situation; testing with your workload is *strongly* recommended before using it in a production environment. These results were achieved using the ["bank" workload](/docs/v26.4/cockroach-workload#bank-workload) running on AWS using 6x c5d.4xlarge nodes, each with 5 TiB of gp2 EBS storage. Results: | Value | Result | | - | - | | vCPU per Node | 16 | | Logical Data per Node | 4.32 TiB | | RAM per Node | 32 GiB | | Data per Core | \~270 GiB / vCPU | | Data per RAM | \~135 GiB / GiB | ### Cloud-specific recommendations Based on our internal testing, we recommend the following cloud-specific configurations. Before using configurations not recommended here, be sure to test them exhaustively. Also consider the following workload-specific observations: * For OLTP applications, small instance types may outperform larger instance types. * Larger, more complex workloads will likely see more consistent performance from instance types with more available memory. * Unless your workload requires extremely high IOPS or very low storage latency, the most cost-effective volumes are general-purpose rather than high-performance volumes. * Because storage cost influences the cost of running a workload much more than instance cost, larger nodes offer a better price-for-performance ratio at the same workload complexity. #### AWS * Use general-purpose [`m6i` or `m6a`](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/general-purpose-instances.html) VMs with SSD-backed [EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html). For example, Cockroach Labs has used `m6i.2xlarge` for performance benchmarking. If your workload requires high throughput, use network-optimized `m5n` instances. To simulate bare-metal deployments, use `m5d` with [SSD Instance Store volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ssd-instance-store.html). * `m5` and `m5a` instances, and [compute-optimized `c5`, `c5a`, and `c5n`](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/compute-optimized-instances.html) instances, are also acceptable. > [!CAUTION] > > **Do not** use [burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html), which limit the load on a single core. * [General Purpose SSD `gp3` volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html#gp3-ebs-volume-type) are a cost-effective storage option. `gp3` volumes provide 3,000 IOPS and 125 MiB/s throughput by default. If your deployment requires more IOPS or throughput, per our [hardware recommendations](#disk-i/o), you must provision these separately. [Provisioned IOPS SSD-backed (`io2`) EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html#EBSVolumeTypes_piops) also need to have IOPS provisioned. * A typical deployment uses [EC2](https://aws.amazon.com/ec2/) together with [key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html), [load balancers](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/load-balancer-types.html), and [security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html). For an example, refer to [Deploy CockroachDB on AWS EC2](/docs/v26.4/deploy-cockroachdb-on-aws). #### Azure * Use general-purpose [Dsv5-series](https://docs.microsoft.com/azure/virtual-machines/dv5-dsv5-series) and [Dasv5-series](https://docs.microsoft.com/azure/virtual-machines/dasv5-dadsv5-series) or memory-optimized [Ev5-series](https://docs.microsoft.com/azure/virtual-machines/ev5-esv5-series) and [Easv5-series](https://docs.microsoft.com/azure/virtual-machines/easv5-eadsv5-series#easv5-series) VMs. For example, Cockroach Labs has used `Standard_D8s_v5`, `Standard_D8as_v5`, `Standard_E8s_v5`, and `Standard_e8as_v5` for performance benchmarking. * Compute-optimized [F-series](https://docs.microsoft.com/azure/virtual-machines/fsv2-series) VMs are also acceptable. > [!CAUTION] > > Do not use ["burstable" B-series](https://docs.microsoft.com/azure/virtual-machines/linux/b-series-burstable) VMs, which limit the load on CPU resources. Also, Cockroach Labs has experienced data corruption issues on A-series VMs, so we recommend avoiding those as well. * Use [Premium Storage](https://docs.microsoft.com/azure/virtual-machines/disks-types#premium-ssds) or local SSD storage with a Linux filesystem such as `ext4` (not the Windows `ntfs` filesystem). Note that [the size of a Premium Storage disk affects its IOPS](https://docs.microsoft.com/azure/virtual-machines/premium-storage-performance#iops). * If you choose local SSD storage, on reboot, the VM can come back with the `ntfs` filesystem. Be sure your automation monitors for this and reformats the disk to the Linux filesystem you chose initially. #### Digital Ocean * Use any [droplets](https://www.digitalocean.com/pricing/) except standard droplets with only 1 GiB of RAM, which is below our minimum requirement. All Digital Ocean droplets use SSD storage. #### GCP * Use general-purpose [`t2d-standard`, `n2-standard`, or `n2d-standard`](https://cloud.google.com/compute/pricing#predefined_machine_types) VMs, or use [custom VMs](https://cloud.google.com/compute/docs/instances/creating-instance-with-custom-machine-type). For example, Cockroach Labs has used `t2d-standard-8`, `n2-standard-8`, and `n2d-standard-8` for performance benchmarking. > [!CAUTION] > > Do not use `f1` or `g1` [shared-core machines](https://cloud.google.com/compute/docs/machine-types#sharedcore), which limit the load on CPU resources. * Use [`pd-ssd` SSD persistent disks](https://cloud.google.com/compute/docs/disks/#pdspecs) or [local SSDs](https://cloud.google.com/compute/docs/disks/#localssds). Note that [the IOPS of SSD persistent disks depends both on the disk size and number of vCPUs on the machine](https://cloud.google.com/compute/docs/disks/performance#optimizessdperformance). * `nobarrier` can be used with SSDs, but only if it has battery-backed write cache. Without one, data can be corrupted in the event of a crash. Cockroach Labs conducts most of our [internal performance tests](https://www.cockroachlabs.com/blog/2018_cloud_report/) using `nobarrier` to demonstrate the best possible performance, but understand that not all use cases can support this option. ## Security An insecure cluster comes with serious risks: * Your cluster is open to any client that can access any node's IP addresses. * Any user, even `root`, can log in without providing a password. * Any user, connecting as `root`, can read or write any data in your cluster. * There is no network encryption or authentication, and thus no confidentiality. Therefore, to deploy CockroachDB in production, it is strongly recommended to [use TLS certificates to authenticate](/docs/v26.4/authentication) the identity of nodes and clients and to encrypt data in transit between nodes and clients. You can use either the built-in [`cockroach cert` commands](/docs/v26.4/cockroach-cert) or [`openssl` commands](/docs/v26.4/create-security-certificates-openssl) to generate security certificates for your deployment. Regardless of which option you choose, you'll need the following files: * A certificate authority (CA) certificate and key, used to sign all of the other certificates. * A separate certificate and key for each node in your deployment, with the common name `node`. * A separate certificate and key for each client and user you want to connect to your nodes, with the common name set to the username. The default user is `root`. If you manage your own Certificate Authority (CA) infrastructure, CockroachDB supports mapping between the Subject field of your [X.509 certificates](https://en.wikipedia.org/wiki/X.509) and SQL [roles](/docs/v26.4/security-reference/authorization#roles). For more information, see [Certificate-based authentication using multiple values from the X.509 Subject field](/docs/v26.4/certificate-based-authentication-using-the-x509-subject-field). Alternatively, CockroachDB supports [password authentication](/docs/v26.4/authentication#client-authentication), although we typically recommend using client certificates instead. For more information, see the [Security Overview](/docs/v26.4/security-reference/security-overview). ## Networking ### Networking flags When [starting a node](/docs/v26.4/cockroach-start#flags-max-offset), two main flags are used to control its network connections: * `--listen-addr` determines which address(es) to listen on for connections from other nodes and clients. * `--advertise-addr` determines which address to tell other nodes to use. The effect depends on how these two flags are used in combination: | | `--listen-addr` not specified | `--listen-addr` specified | | - | - | - | | **`--advertise-addr` not specified** | Node listens on all of its IP addresses on port `26257` and advertises its canonical hostname to other nodes. | Node listens on the IP address/hostname and port specified in `--listen-addr` and advertises this value to other nodes. | | **`--advertise-addr` specified** | Node listens on all of its IP addresses on port `26257` and advertises the value specified in `--advertise-addr` to other nodes. **Recommended for most cases.** | Node listens on the IP address/hostname and port specified in `--listen-addr` and advertises the value specified in `--advertise-addr` to other nodes. If the `--advertise-addr` port number is different than the one used in `--listen-addr`, port forwarding is required. | > [!TIP] > > When using hostnames, make sure they resolve properly (e.g., via DNS or `etc/hosts`). In particular, be careful about the value advertised to other nodes, either via `--advertise-addr` or via `--listen-addr` when `--advertise-addr` is not specified. ### Cluster on a single network When running a cluster on a single network, the setup depends on whether the network is private. In a private network, machines have addresses restricted to the network, not accessible to the public internet. Using these addresses is more secure and usually provides lower latency than public addresses. | Private? | Recommended setup | | - | - | | Yes | Start each node with `--listen-addr` set to its private IP address and do not specify `--advertise-addr`. This will tell other nodes to use the private IP address advertised. Load balancers/clients in the private network must use it as well. | | No | Start each node with `--advertise-addr` set to a stable public IP address that routes to the node and do not specify `--listen-addr`. This will tell other nodes to use the specific IP address advertised, but load balancers/clients will be able to use any address that routes to the node. If load balancers/clients are outside the network, also configure firewalls to allow external traffic to reach the cluster. | ### Cluster spanning multiple networks When running a cluster across multiple networks, the setup depends on whether nodes can reach each other across the networks. | Nodes reachable across networks? | Recommended setup | | - | - | | Yes | This is typical when all networks are on the same cloud. In this case, use the relevant [single network setup](#cluster-on-a-single-network) above. | | No | This is typical when networks are on different clouds. In this case, set up a [VPN](https://wikipedia.org/wiki/Virtual_private_network), [VPC](https://wikipedia.org/wiki/Virtual_private_cloud), [NAT](https://wikipedia.org/wiki/Network_address_translation), or another such solution to provide unified routing across the networks. Then start each node with `--advertise-addr` set to the address that is reachable from other networks and do not specify `--listen-addr`. This will tell other nodes to use the specific IP address advertised, but load balancers/clients will be able to use any address that routes to the node. Also, if a node is reachable from other nodes in its network on a private or local address, set [`--locality-advertise-addr`](/docs/v26.4/cockroach-start#networking) to that address. This will tell nodes within the same network to prefer the private or local address to improve performance. Note that this feature requires that each node is started with the [`--locality`](/docs/v26.4/cockroach-start#locality) flag. For more details, see this [example](/docs/v26.4/cockroach-start#start-a-multi-node-cluster-across-private-networks). | ## Load balancing Each CockroachDB node is an equally suitable SQL gateway to a cluster, but to ensure client performance and reliability, it's important to use load balancing: * **Performance:** Load balancers spread client traffic across nodes. This prevents any one node from being overwhelmed by requests and improves overall cluster performance (queries per second). * **Reliability:** Load balancers decouple client health from the health of a single CockroachDB node. To ensure that traffic is not directed to failed nodes or nodes that are not ready to receive requests, load balancers should use [CockroachDB's readiness health check](/docs/v26.4/monitoring-and-alerting). > [!TIP] > > With a single load balancer, client connections are resilient to node failure, but the load balancer itself is a point of failure. It's therefore best to make load balancing resilient as well by using multiple load balancing instances, with a mechanism like floating IPs or DNS to select load balancers for clients. For guidance on load balancing, see the tutorial for your deployment environment: | Environment | Featured Approach | | - | - | | [On-Premises](/docs/v26.4/deploy-cockroachdb-on-premises#step-6-set-up-load-balancing) | Use HAProxy. | | [AWS](/docs/v26.4/deploy-cockroachdb-on-aws#step-4-set-up-load-balancing) | Use Amazon's managed load balancing service. | | [Azure](/docs/v26.4/deploy-cockroachdb-on-microsoft-azure#step-4-set-up-load-balancing) | Use Azure's managed load balancing service. | | [Digital Ocean](/docs/v26.4/deploy-cockroachdb-on-digital-ocean#step-3-set-up-load-balancing) | Use Digital Ocean's managed load balancing service. | | [GCP](/docs/v26.4/deploy-cockroachdb-on-google-cloud-platform#step-4-set-up-load-balancing) | Use GCP's managed TCP proxy load balancing service. | ## Connection pooling Creating the appropriate size pool of connections is critical to gaining maximum performance in an application. Too few connections in the pool will result in high latency as each operation waits for a connection to open up. But adding too many connections to the pool can also result in high latency as each connection thread is being run in parallel by the system. The time it takes for many threads to complete in parallel is typically higher than the time it takes a smaller number of threads to run sequentially. The number of **active** connections across all connection pools **should not exceed 4 times the number of vCPUs** in the cluster by a large amount. A connection is "active" when it is actively executing a query. To monitor active connections, use the [**Active SQL Statements** graph and `sql.statements.active` metric](/docs/v26.4/connection-pooling#monitor-active-connections). For guidance on sizing, validating, and using connection pools with CockroachDB, refer to [Use Connection Pools](/docs/v26.4/connection-pooling). To control the maximum number of non-superuser ([`root`](/docs/v26.4/security-reference/authorization) user or other [`admin` role](/docs/v26.4/security-reference/authorization#admin-role)) connections a [gateway node](/docs/v26.4/architecture/sql-layer) can have open at one time, use the `server.max_connections_per_gateway` [cluster setting](/docs/v26.4/cluster-settings). If a new non-superuser connection would exceed this limit, the error message `"sorry, too many clients already"` is returned, along with error code `53300`. ## Monitoring and alerting Despite CockroachDB's various [built-in safeguards against failure](/docs/v26.4/frequently-asked-questions#how-does-cockroachdb-survive-failures), it is critical to actively monitor the overall health and performance of a cluster running in production and to create alerting rules that promptly send notifications when there are events that require investigation or intervention. For details about available monitoring options and the most important events and metrics to alert on, see [Monitoring and Alerting](/docs/v26.4/monitoring-and-alerting). ## Backup and restore CockroachDB is purpose-built to be fault-tolerant and to recover automatically, but sometimes disasters happen. Having a [disaster recovery](/docs/v26.4/disaster-recovery-planning) plan enables you to recover quickly, while limiting the consequences. Taking regular backups of your data in production is an operational best practice. You can create [full](/docs/v26.4/take-full-and-incremental-backups#full-backups) or [incremental](/docs/v26.4/take-full-and-incremental-backups#incremental-backups) backups of a cluster, database, or table. We recommend taking backups to [cloud storage](/docs/v26.4/use-cloud-storage) and enabling [object locking](/docs/v26.4/use-cloud-storage#immutable-storage) to protect the validity of your backups. CockroachDB supports Amazon S3, Azure Storage, and Google Cloud Storage for backups. For details about available backup and restore types in CockroachDB, see [Backup and restore types](/docs/v26.4/backup-and-restore-overview#backup-and-restore-support). ## Clock synchronization CockroachDB requires moderate levels of clock synchronization to preserve data consistency. For this reason, when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed, it spontaneously shuts down. This offset defaults to 500ms but can be changed via the [`--max-offset`](/docs/v26.4/cockroach-start#flags-max-offset) flag when starting each node. Regardless of clock skew, [`SERIALIZABLE`](/docs/v26.4/demo-serializable) and [`READ COMMITTED`](/docs/v26.4/read-committed) transactions both serve globally consistent ("non-stale") reads and [commit atomically](/docs/v26.4/developer-basics#how-transactions-work-in-cockroachdb). However, skew outside the configured clock offset bounds can result in violations of single-key linearizability between causally dependent transactions. It's therefore important to prevent clocks from drifting too far by running [NTP](http://www.ntp.org/) or other clock synchronization software on each node. In very rare cases, CockroachDB can momentarily run with a stale clock. This can happen when using vMotion, which can suspend a VM running CockroachDB, migrate it to different hardware, and resume it. This will cause CockroachDB to be out of sync for a short period before it jumps to the correct time. During this window, it would be possible for a client to read stale data and write data derived from stale reads. By enabling the `server.clock.forward_jump_check_enabled` [cluster setting](/docs/v26.4/cluster-settings), you can be alerted when the CockroachDB clock jumps forward, indicating it had been running with a stale clock. To protect against this on vMotion, however, use the [`--clock-device`](/docs/v26.4/cockroach-start#general) flag to specify a [PTP hardware clock](https://www.kernel.org/doc/html/latest/driver-api/ptp.html) for CockroachDB to use when querying the current time. When doing so, you should not enable `server.clock.forward_jump_check_enabled` because forward jumps will be expected and harmless. For more information on how `--clock-device` interacts with vMotion, refer to [this blog post](https://web.archive.org/web/20210420062611/https://core.vmware.com/blog/cockroachdb-vmotion-support-vsphere-7-using-precise-timekeeping). ### Considerations When setting up clock synchronization: * All nodes in the cluster must be synced to the same time source, or to different sources that implement leap second smearing in the same way. For example, Google and Amazon have time sources that are compatible with each other (they implement [leap second smearing](https://developers.google.com/time/smear) in the same way), but are incompatible with the default NTP pool (which does not implement leap second smearing). * For nodes running in AWS, we recommend [Amazon Time Sync Service](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure-amazon-time-service). For nodes running in GCP, we recommend [Google's internal NTP service](https://cloud.google.com/compute/docs/instances/configure-ntp#configure_ntp_for_your_instances). For nodes running elsewhere, we recommend [Google Public NTP](https://developers.google.com/time/). Note that the Google and Amazon time services can be mixed with each other, but they cannot be mixed with other time services (unless you have verified leap second behavior). Either all of your nodes should use the Google and Amazon services, or none of them should. * If you do not want to use the Google or Amazon time sources, you can use [`chrony`](https://chrony.tuxfamily.org/index.html) and enable client-side leap smearing, unless the time source you're using already does server-side smearing. In most cases, we recommend the Google Public NTP time source because it handles smearing the leap second. If you use a different NTP time source that doesn't smear the leap second, you must configure client-side smearing manually and do so in the same way on each machine. * Do not run more than one clock sync service on VMs where `cockroach` is running. * For new clusters using the [multi-region SQL abstractions](/docs/v26.4/multiregion-overview), Cockroach Labs recommends lowering the [`--max-offset`](/docs/v26.4/cockroach-start#flags-max-offset) setting to `250ms`. This setting is especially helpful for lowering the write latency of [global tables](/docs/v26.4/table-localities#global-tables). Nodes can run with different values for `--max-offset`, but only for the purpose of updating the setting across the cluster using a rolling upgrade. ### Tutorials For guidance on synchronizing clocks, see the tutorial for your deployment environment: | Environment | Featured Approach | | - | - | | [On-Premises](/docs/v26.4/deploy-cockroachdb-on-premises#step-1-synchronize-clocks) | Use NTP with Google's external NTP service. | | [AWS](/docs/v26.4/deploy-cockroachdb-on-aws#step-3-synchronize-clocks) | Use the Amazon Time Sync Service. | | [Azure](/docs/v26.4/deploy-cockroachdb-on-microsoft-azure#step-3-synchronize-clocks) | Disable Hyper-V time synchronization and use NTP with Google's external NTP service. | | [Digital Ocean](/docs/v26.4/deploy-cockroachdb-on-digital-ocean#step-2-synchronize-clocks) | Use NTP with Google's external NTP service. | | [GCE](/docs/v26.4/deploy-cockroachdb-on-google-cloud-platform#step-3-synchronize-clocks) | Use NTP with Google's internal NTP service. | ## Cache and SQL memory size CockroachDB manages its own memory caches, independently of the operating system. These are configured via the [`--cache`](/docs/v26.4/cockroach-start#flags) and [`--max-sql-memory`](/docs/v26.4/cockroach-start#flags) flags. The default cache size is per-node and is passively consumed; it was chosen to facilitate development and testing, where users are likely to run multiple CockroachDB nodes on a single machine. Increasing the cache size will generally improve the node's read performance. Production systems should always configure this setting. The [`--cache`](/docs/v26.4/cockroach-start#flags) flag controls the [Pebble storage engine](/docs/v26.4/architecture/storage-layer#pebble) block cache, which holds uncompressed blocks of persisted [key-value data](/docs/v26.4/architecture/distribution-layer#overview) in memory. If a read misses within the block cache, the storage engine reads the file via the operating system's page cache, which may hold the relevant block in-memory in its compressed form. Otherwise, the read is served from the storage device. The block cache fills to the configured size and is then recycled using a least-recently-used (LRU) policy. Each node has a default SQL memory size of `25%`. This memory is used as-needed by active operations to store temporary data for SQL queries. * Increasing a node's **cache size** will improve the node's read performance. * Increasing a node's **SQL memory size** will increase the number of simultaneous client connections it allows, as well as the node's capacity for in-memory processing of rows when using `ORDER BY`, `GROUP BY`, `DISTINCT`, joins, and window functions. > [!NOTE] > > SQL memory size applies a limit globally to all sessions at any point in time. Certain disk-spilling operations also respect a memory limit that applies locally to a single operation within a single query. This limit is configured via a separate cluster setting. For details, see [Disk-spilling operations](/docs/v26.4/vectorized-execution#disk-spilling-operations). If a node runs out of its allocated SQL memory, a `memory budget exceeded` error occurs and the `cockroach` process may be at risk of crashing due to an out-of-memory (OOM) error. To mitigate this issue, refer to [\`memory budget exceeded](/docs/v26.4/common-errors#memory-budget-exceeded). To manually increase a node's cache size and SQL memory size, start the node using the [`--cache`](/docs/v26.4/cockroach-start#flags) and [`--max-sql-memory`](/docs/v26.4/cockroach-start#flags) flags. As long as all machines are [provisioned with sufficient RAM](#memory), you can experiment with increasing each value up to `35%`. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach start --cache=.35 --max-sql-memory=.35 {other start flags} ``` The default value for `--cache` is 128 MiB. For production deployments, set `--cache` to `25%` or higher. To determine appropriate settings for `--cache` and `--max-sql-memory`, use the following formula:
`(2 * --max-sql-memory) + --cache <= 80% of system RAM
`
To help guard against [OOM events](/docs/v26.4/cluster-setup-troubleshooting#out-of-memory-oom-crash), CockroachDB sets a soft memory limit using mechanisms in Go. Depending on your hardware and workload, you may not need to manually tune `--max-sql-memory`. Test the configuration with a reasonable workload before deploying it to production. > [!NOTE] > > On startup, if CockroachDB detects that `--max-sql-memory` or `--cache` are set too aggressively, a warning is logged. Because CockroachDB manages its own memory caches, Cockroach Labs recommends that you disable Linux memory swapping or allocate sufficient RAM to each node to prevent the node from running low on memory. Writing to swap is significantly less performant than writing to memory. ## Dependencies The [CockroachDB binary for Linux](/docs/v26.4/install-cockroachdb-linux) depends on the following libraries: | Library | Description | | - | - | | [`glibc`](https://www.gnu.org/software/libc/libc.html) | The standard C library. If you build CockroachDB from source, rather than use the official CockroachDB binary for Linux, you can use any C standard library, including MUSL, the C standard library used on Alpine. | | `libncurses` | Required by the [built-in SQL shell](/docs/v26.4/cockroach-sql). | | [`tzdata`](https://www.iana.org/time-zones) | Required by certain features of CockroachDB that use time zone data, for example, to support using location-based names as time zone identifiers. This library is sometimes called `tz` or `zoneinfo`. The CockroachDB binary now includes Go's copy of the `tzdata` library. If CockroachDB cannot find the `tzdata` library externally, it will use this built-in copy. | These libraries are found by default on nearly all Linux distributions, with Alpine as the notable exception, but it's nevertheless important to confirm that they are installed and kept up-to-date. For the time zone data in particular, it's important for all nodes to have the same version; when updating the library, do so as quickly as possible across all nodes. > [!NOTE] > > In Docker-based deployments of CockroachDB, these dependencies do not need to be manually addressed. The Docker image for CockroachDB includes them and keeps them up to date with each release of CockroachDB. ## File descriptors limit CockroachDB can use a large number of open file descriptors, often more than is available by default. Therefore, note the following recommendations. For each CockroachDB node: * At a **minimum**, the file descriptors limit must be `1956` (1700 per store plus 256 for networking). If the limit is below this threshold, the node will not start. * It is **recommended** to set the file descriptors limit to `unlimited`; otherwise, the recommended limit is at least `15000` (10000 per store plus 5000 for networking). This higher limit ensures performance and accommodates cluster growth. * When the file descriptors limit is not high enough to allocate the recommended amounts, CockroachDB allocates 10000 per store and the rest for networking; if this would result in networking getting less than 256, CockroachDB instead allocates 256 for networking and evenly splits the rest across stores. ### Increase the file descriptors limit * [Yosemite and later](#yosemite-and-later) * [Older versions](#older-versions) #### Yosemite and later To adjust the file descriptors limit for a single process in Mac OS X Yosemite and later, you must create a property list configuration file with the hard limit set to the recommendation mentioned [above](#file-descriptors-limit). Note that CockroachDB always uses the hard limit, so it's not technically necessary to adjust the soft limit, although we do so in the steps below. For example, for a node with 3 stores, we would set the hard limit to at least 35000 (10000 per store and 5000 for networking) as follows: 1. Check the current limits: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ launchctl limit maxfiles ``` ``` maxfiles 10240 10240 ``` The last two columns are the soft and hard limits, respectively. If `unlimited` is listed as the hard limit, note that the hidden default limit for a single process is actually 10240. 2. Create `/Library/LaunchDaemons/limit.maxfiles.plist` and add the following contents, with the final strings in the `ProgramArguments` array set to 35000: ```xml theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Labellimit.maxfilesProgramArguments launchctllimitmaxfiles3500035000RunAtLoad ServiceIPC /proc/sys/fs/file-max ``` CockroachDB for Windows is experimental and not supported in production. To learn about configuring limits on Windows, refer to the Microsoft community blog post [Pushing the Limits of Windows: Handles](https://techcommunity.microsoft.com/t5/windows-blog-archive/pushing-the-limits-of-windows-handles/ba-p/723848). #### Attributions This section, "File Descriptors Limit", is in part derivative of the chapter *Open File Limits* From the Riak LV 2.1.4 documentation, used under Creative Commons Attribution 3.0 Unported License. ## Orchestration / Kubernetes When running CockroachDB on Kubernetes, making the following minimal customizations will result in better, more reliable performance: * Use [SSDs instead of traditional HDDs](/docs/v26.4/kubernetes-performance#disk-type). * Configure CPU and memory [resource requests and limits](/docs/v26.4/kubernetes-performance#resource-requests-and-limits). For more information and additional customization suggestions, see our full detailed guide to [CockroachDB Performance on Kubernetes](/docs/v26.4/kubernetes-performance). ## Transaction retries When several transactions try to modify the same underlying data concurrently, they may experience [contention](/docs/v26.4/performance-best-practices-overview#transaction-contention) that leads to [transaction retries](/docs/v26.4/transactions#transaction-retries). To avoid failures in production, your application should be engineered to handle transaction retries using [client-side retry handling](/docs/v26.4/transaction-retry-error-reference#client-side-retry-handling). # Regional Tables Source: https://docs.cockroachlabs.com/docs/stable/regional-tables In a [multi-region deployment](/docs/v26.4/multiregion-overview#table-locality), [regional table locality](/docs/v26.4/multiregion-overview#table-locality) is a good choice for tables with the following requirements: * Read and write latency must be low. * Rows in the table, and all latency-sensitive queries, can be tied to specific regions. Tables with regional table locality can survive zone or region failures, depending on the database-level [survival goal](/docs/v26.4/multiregion-overview#survival-goals) setting. For new clusters using the [multi-region SQL abstractions](/docs/v26.4/multiregion-overview#table-locality), Cockroach Labs recommends lowering the [`--max-offset`](/docs/v26.4/cockroach-start#flags-max-offset) setting to `250ms`. This setting is especially helpful for lowering the write latency of [global tables](/docs/v26.4/table-localities#global-tables). Nodes can run with different values for `--max-offset`, but only for the purpose of updating the setting across the cluster using a rolling upgrade. ## Before you begin ### Fundamentals Multi-region patterns require thinking about the following questions: * What are your [survival goals](/docs/v26.4/multiregion-overview#survival-goals)? Do you need to survive a [zone failure](/docs/v26.4/multiregion-survival-goals#survive-zone-failures)? Do you need to survive a [region failure](/docs/v26.4/multiregion-survival-goals#survive-region-failures)? * What are the [table localities](/docs/v26.4/multiregion-overview#table-locality) that will provide the performance characteristics you need for each table's data? * Do you need low-latency reads and writes from a single region? Do you need that single region to be configurable at the [row level](/docs/v26.4/table-localities#regional-by-row-tables)? Or will [a single optimized region for the entire table](/docs/v26.4/table-localities#regional-tables) suffice? * Do you have a "read-mostly" [table of reference data that is rarely updated](/docs/v26.4/table-localities#global-tables), but that must be read with low latency from all regions? For more information about CockroachDB multi-region capabilities, review the following pages: * [Multi-Region Capabilities Overview](/docs/v26.4/multiregion-overview#table-locality) * [How to Choose a Multi-Region Configuration](/docs/v26.4/choosing-a-multi-region-configuration) * [When to use `ZONE` vs. `REGION` Survival Goals](/docs/v26.4/multiregion-survival-goals#when-to-use-zone-vs-region-survival-goals) * [When to use `REGIONAL` vs. `GLOBAL` Tables](/docs/v26.4/table-localities#when-to-use-regional-vs-global-tables) In addition, reviewing the following information will be helpful: * The concept of [locality](/docs/v26.4/cockroach-start#locality), which CockroachDB uses to place and balance data based on how you define survival goal and table locality settings. * The recommendations in our [Production Checklist](/docs/v26.4/recommended-production-settings), including our [hardware recommendations](/docs/v26.4/recommended-production-settings#hardware). Afterwards, perform a proof of concept to size hardware for your use case. * [SQL Performance Best Practices](/docs/v26.4/performance-best-practices-overview) ### Cluster setup Each [multi-region pattern](/docs/v26.4/topology-patterns#multi-region) assumes the following setup: ![Multi-region hardware setup](https://mintcdn.com/cockroachlabs/iiBVxthghoAOO3UM/images/common/topology-patterns/topology_multi-region_hardware.png?fit=max\&auto=format\&n=iiBVxthghoAOO3UM\&q=85\&s=810cffba5f7294be67bc34e0b3276c28) #### Hardware * 3 regions * Per region, 3+ AZs with 3+ VMs evenly distributed across them * Region-specific app instances and load balancers * Each load balancer redirects to CockroachDB nodes in its region. * When CockroachDB nodes are unavailable in a region, the load balancer redirects to nodes in other regions. #### Cluster startup Start each node with the [`--locality`](/docs/v26.4/cockroach-start#locality) flag specifying its region and AZ combination. For example, the following command starts a node in the `west1` AZ of the `us-west` region: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} $ cockroach start \ --locality=region=us-west,zone=west1 \ --certs-dir=certs \ --advertise-addr=