---
title: How to Deploy Apache Cassandra as a Self-Hosted Amazon Keyspaces Alternative
url: https://docs.vultr.com/how-to-deploy-apache-cassandra-as-a-self-hosted-amazon-keyspaces-alternative
description: Deploy a three-node Apache Cassandra 5.0 cluster on Vultr as an Amazon Keyspaces alternative, with authentication, Medusa backups, and Keyspaces migration.
publish_date: 2026-12-03T19:27:01.311041Z
last_updated: 2026-12-03T20:46:10.944358Z
author: Vijay  Srinivas P
header_image: https://assets.vultrdevrel.com/docs-main-doc-assets-1/2695/a7bbd524-ba2f-4751-84fd-60c17026ed3d.png
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

[Amazon Keyspaces](https://aws.amazon.com/keyspaces/) is a serverless AWS database service that implements the Cassandra 3.11 Cassandra Query Language (CQL) API. It removes server management and scales capacity automatically, but it supports only a subset of Cassandra features and consistency levels, bills for every request or for provisioned capacity, and ties your data to a single cloud provider.

[Apache Cassandra](https://cassandra.apache.org/) is an open-source, distributed NoSQL database that replicates data across multiple nodes without a single point of failure. Applications connect to it with the same CQL drivers they use with Keyspaces, and a self-hosted Cassandra 5.0 cluster gives you full control over consistency levels, compaction, caching, and repair, at the fixed cost of the servers that you run.

This article explains how to deploy Apache Cassandra as an alternative to Amazon Keyspaces. It covers a three-node Cassandra 5.0 cluster in a private network with password authentication and three replicas of every row, a node failure test, daily backups to S3-compatible object storage with Cassandra Medusa, optional monitoring with Prometheus and Grafana, and the migration of existing Keyspaces tables and applications.

## Understanding Cassandra Architecture

A self-hosted cluster serves the same CQL tables as Amazon Keyspaces and adds the servers, replication, backups, and monitoring that Keyspaces manages for you. The following table maps Keyspaces concepts to their equivalents in this deployment.

| Amazon Keyspaces | Apache Cassandra Equivalent | Description |
|---|---|---|
| Keyspace with `SingleRegionStrategy` | Keyspace with `NetworkTopologyStrategy` and `'dc1': 3` | Stores three copies of every row, one on each rack. |
| CQL tables and Cassandra drivers | The same CQL tables and drivers | Keyspaces implements the Cassandra 3.11 API, and this cluster runs Cassandra 5.0. |
| Read consistency `ONE`, `LOCAL_ONE`, and `LOCAL_QUORUM`, writes at `LOCAL_QUORUM` | Every Cassandra consistency level | This article uses `LOCAL_QUORUM`, which needs two of the three replicas. |
| IAM authentication with SigV4 or service-specific credentials | `PasswordAuthenticator` and `CassandraAuthorizer` | Authenticates CQL roles stored in the `system_auth` keyspace. |
| TLS endpoint on port `9142` | CQL on port `9042` inside the private network | Accepts client connections on private IP addresses only. Configure `client_encryption_options` for clients outside the private network. |
| AWS PrivateLink interface endpoints | Private network | Keeps database traffic on private IP addresses. |
| On-demand and provisioned capacity with auto scaling | Three nodes with a fixed capacity | Grows when you add nodes, three at a time with one per rack, or resize them one node at a time. |
| Point-in-time recovery for the previous 35 days | Medusa daily backups to S3-compatible object storage | Restores to the time of a daily backup and keeps the seven most recent backups. |
| Amazon CloudWatch metrics | Prometheus, the JMX exporter, Node Exporter, and Grafana | Collects request, latency, compaction, and server metrics, and evaluates six alert rules. |
| Multi-Region replication | No direct equivalent in this article | Add a second datacenter in another region to each keyspace. |
| Encryption at rest with AWS KMS keys | No direct equivalent | Cassandra does not encrypt SSTable data files. Use disk encryption on the servers if your policy requires it. |
| Serverless operation | No direct equivalent | You run upgrades, repairs, and node replacement. |

Each of the three Cassandra servers runs a Cassandra node, two metrics exporters, and Medusa, and the first server also runs the client tools. The fourth server runs only Prometheus and Grafana, so monitoring continues when a node fails.

![Architecture in which three Apache Cassandra nodes replicate over a private network, back up to S3-compatible object storage with Medusa, and send metrics to Prometheus and Grafana on a separate monitoring server.](https://assets.vultrdevrel.com/docs-main-doc-assets-1/2695/22ddc8b5-f417-4fee-844f-5e5735de22a9.png)

The deployment uses one datacenter named `dc1` with three racks named `rack1`, `rack2`, and `rack3`, one node per rack, and all three nodes act as seeds. Cassandra traffic stays on the private network, and backups leave each node as outbound HTTPS traffic to object storage.

The commands in this article use the following placeholders:

* `NODE1_IP`, `NODE2_IP`, and `NODE3_IP`: The private IP addresses of the first, second, and third node, shown in the `ip -4 addr` output of the private network interface.
* `NODE_PRIVATE_IP`: The private IP address of the node that you are configuring.
* `PEER_IP`: The private IP address of another cluster node, used in firewall rules.
* `MONITOR_IP` and `MONITOR_PUBLIC_IP`: The private IP address and the public IP address of the monitoring server.
* `DBA_USER` and `DBA_PASSWORD`: The name and password of the administrative superuser role that you create, such as `dbadmin`.
* `MEDUSA_PASSWORD`: The password of the Medusa backup role.
* `OBJECT_STORAGE_HOSTNAME`: The endpoint hostname of your object storage service, without the `https://` prefix.
* `ACCESS_KEY` and `SECRET_KEY`: The access key and secret key of your object storage service.
* `ROW_ID`: An `id` value from the test table.
* `BACKUP_NAME`: The name of a Medusa backup, such as `initial`.
* `REGION`: The AWS Region of your Amazon Keyspaces tables, such as `us-east-1`.
* `KEYSPACE_NAME` and `TABLE_NAME`: The keyspace and table that you migrate from Amazon Keyspaces.
* `SERVICE_USER` and `SERVICE_PASSWORD`: The Amazon Keyspaces service-specific credentials.

## Prerequisites

Before you begin:

* Have access to three [Ubuntu 26.04 servers](https://docs.vultr.com/products/compute/instances/cloud-compute/provisioning) in the same region for the Cassandra nodes, each with at least 8 vCPUs, 32 GB of memory, and 100 GB of storage. This size follows the [hardware guidance in the Apache Cassandra documentation](https://cassandra.apache.org/doc/stable/cassandra/managing/operating/hardware.html).
* (Optional) Have access to a fourth, smaller Ubuntu 26.04 server in the same region for monitoring, such as one with 2 vCPUs and 4 GB of memory.
* Connect all four servers to the same [private network](https://docs.vultr.com/products/compute/instances/cloud-compute/networking/vpc).
* Have access to an [S3-compatible object storage](https://docs.vultr.com/products/storage/object-storage/provisioning) service, and note its endpoint hostname, access key, and secret key. A location in the same region gives the fastest backups and restores, and a different region keeps the backups available during a regional outage.
* Access each server using SSH as a [non-root user with sudo privileges](https://docs.vultr.com/how-to-create-a-sudo-user-on-a-linux-server), with the `ServerAliveInterval` SSH option enabled, and run long commands, such as package upgrades, inside a `tmux` session.
* (Optional) Create [service-specific credentials](https://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.credentials.ssc.html) for an IAM user with the `cassandra:Select` permission on the Amazon Keyspaces tables that you plan to migrate and on the system tables (`/keyspace/system*`), which `cqlsh` and Cassandra drivers read when they connect.

## Update the System and Install Java 17

Cassandra 5.0 runs on Java 11 or Java 17 only, and the default Java package on recent Ubuntu releases installs a newer version. Install OpenJDK 17 explicitly and set it as the default runtime. Run the steps on all three Cassandra servers.

1. Update the package index and upgrade the installed packages.

    ```console
    $ sudo apt update && sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y
    ```

1. Install the repository tools and the OpenJDK 17 runtime.

    ```console
    $ sudo apt install -y curl gnupg ca-certificates openjdk-17-jre-headless
    ```

1. Set Java 17 as the default Java runtime.

    ```console
    $ sudo update-alternatives --set java $(update-alternatives --list java | grep -- '-17-' | head -n1)
    ```

1. Verify the active Java version.

    ```console
    $ java -version
    ```

    The first line of the output begins with `openjdk version "17`.

## Install the Cassandra Package

The Apache Cassandra project publishes Debian packages in its own APT repository, and the `50x` distribution contains the Cassandra 5.0 series. Run the steps on all three Cassandra servers.

1. Download the Apache Cassandra repository signing keys.

    ```console
    $ sudo mkdir -p /etc/apt/keyrings
    $ sudo curl -fsSL -o /etc/apt/keyrings/apache-cassandra.asc https://downloads.apache.org/cassandra/KEYS
    ```

1. Add the Cassandra 5.0 repository to the APT sources.

    ```console
    $ echo "deb [signed-by=/etc/apt/keyrings/apache-cassandra.asc] https://debian.cassandra.apache.org 50x main" | sudo tee /etc/apt/sources.list.d/cassandra.sources.list
    ```

1. Update the package index and install Cassandra.

    ```console
    $ sudo apt update && sudo apt install -y cassandra
    ```

1. Verify the installed Cassandra version.

    ```console
    $ cassandra -v
    ```

    The output displays a version in the 5.0 series.

## Remove the Default Single-Node Data

The package starts Cassandra immediately with a default single-node configuration named `Test Cluster`. A node that keeps this data later refuses to start with the error `Saved cluster name Test Cluster != configured name`, so stop Cassandra and remove the data. Run the steps on all three Cassandra servers.

1. Stop the Cassandra service.

    ```console
    $ sudo systemctl stop cassandra
    ```

1. Stop the process that the package started. The package launches Cassandra during installation, before systemd tracks the service, so `systemctl stop` can miss that first instance. Later starts and stops through systemd are not affected.

    ```console
    $ sudo pkill -f CassandraDaemon
    ```

1. Verify that no Cassandra process is running.

    ```console
    $ pgrep -f CassandraDaemon
    ```

    The command prints no output. If it prints a process ID, wait a few seconds and run it again.

1. Delete the default data, commit log, saved caches, and hints.

    ```console
    $ sudo find /var/lib/cassandra/data /var/lib/cassandra/commitlog \
        /var/lib/cassandra/saved_caches /var/lib/cassandra/hints \
        -mindepth 1 -delete
    ```

    Do not replace this with `sudo rm -rf /var/lib/cassandra/data/*`. The non-root shell expands the `*` wildcard before `sudo` runs and cannot read the Cassandra directories, so that command deletes nothing.

1. Verify that the data directory is empty.

    ```console
    $ sudo ls -A /var/lib/cassandra/data
    ```

    The command prints no output.

## Tune the Operating System

Cassandra uses many memory-mapped regions, and swapping memory to disk degrades its performance. The Cassandra package init script already raises the open file limit and the locked memory limit of the Cassandra process, so no limits file is required. Increase the kernel limit for memory-mapped areas and disable swap. Run the steps on all three Cassandra servers.

1. Increase the maximum number of memory-mapped areas.

    ```console
    $ echo "vm.max_map_count = 1048575" | sudo tee /etc/sysctl.d/60-cassandra.conf
    ```

1. Apply the kernel setting.

    ```console
    $ sudo sysctl -p /etc/sysctl.d/60-cassandra.conf
    ```

    The output displays `vm.max_map_count = 1048575`.

1. Disable swap, and comment out the swap entries in the `/etc/fstab` file to keep swap disabled after a reboot.

    ```console
    $ sudo swapoff -a
    $ sudo sed -i '/\sswap\s/ s/^/#/' /etc/fstab
    ```

1. Verify that swap is disabled.

    ```console
    $ swapon --show
    $ free -h
    ```

    The `swapon` command prints no output, and the `Swap` row of the `free` output displays `0B`.

## Configure the Cluster Settings

Every node needs the same cluster name, seed list, snitch, and authentication settings, plus its own listen address and rack. The following `sed` commands produce the same result on every node. Run the steps on all three Cassandra servers.

1. Back up the default configuration file.

    ```console
    $ sudo cp /etc/cassandra/cassandra.yaml /etc/cassandra/cassandra.yaml.backup
    ```

1. Store the private IP address of the node in a shell variable, and print it to verify it. The command uses `enp8s0` as the private network interface. Replace it with the name of your private interface from the `ip -4 addr` output.

    ```console
    $ NODE_IP=$(ip -4 -o addr show enp8s0 | awk '{print $4}' | cut -d/ -f1)
    $ echo $NODE_IP
    ```

1. Set the cluster name, which must be the same on every node.

    ```console
    $ sudo sed -i "s|^cluster_name:.*|cluster_name: 'Production Cassandra Cluster'|" /etc/cassandra/cassandra.yaml
    ```

1. Replace `NODE1_IP`, `NODE2_IP`, and `NODE3_IP` with the private IP addresses of the three nodes, and set the seed list, which must be the same on every node.

    ```console
    $ sudo sed -i "s|^\([[:space:]]*\)- seeds:.*|\1- seeds: \"NODE1_IP,NODE2_IP,NODE3_IP\"|" /etc/cassandra/cassandra.yaml
    ```

1. Bind inter-node and client traffic to the private IP address.

    ```console
    $ sudo sed -i "s|^listen_address:.*|listen_address: $NODE_IP|" /etc/cassandra/cassandra.yaml
    $ sudo sed -i "s|^rpc_address:.*|rpc_address: $NODE_IP|" /etc/cassandra/cassandra.yaml
    ```

1. Set the snitch to `GossipingPropertyFileSnitch`, which reads the datacenter and rack of each node from a properties file.

    ```console
    $ sudo sed -i "s|^endpoint_snitch:.*|endpoint_snitch: GossipingPropertyFileSnitch|" /etc/cassandra/cassandra.yaml
    ```

1. Enable password authentication and role-based authorization.

    ```console
    $ sudo sed -i "s|^authenticator:.*|authenticator: PasswordAuthenticator|" /etc/cassandra/cassandra.yaml
    $ sudo sed -i "s|^authorizer:.*|authorizer: CassandraAuthorizer|" /etc/cassandra/cassandra.yaml
    ```

1. Set the datacenter and rack of the node. Use `rack1` on the first node, `rack2` on the second node, and `rack3` on the third node.

    ```console
    $ printf "dc=dc1\nrack=rack1\n" | sudo tee /etc/cassandra/cassandra-rackdc.properties
    ```

1. Verify the settings in the configuration file.

    ```console
    $ grep -nE "^cluster_name:|- seeds:|^listen_address:|^rpc_address:|^endpoint_snitch:|^authenticator:|^authorizer:" /etc/cassandra/cassandra.yaml
    ```

    The output on the first node resembles the following, with your private IP addresses in place of the placeholders:

    ```
    26:cluster_name: 'Production Cassandra Cluster'
    198:authenticator: PasswordAuthenticator
    217:authorizer: CassandraAuthorizer
    706:      - seeds: "NODE1_IP,NODE2_IP,NODE3_IP"
    981:listen_address: NODE1_IP
    1090:rpc_address: NODE1_IP
    1556:endpoint_snitch: GossipingPropertyFileSnitch
    ```

## Configure the Firewall

Uncomplicated Firewall (UFW) filters traffic on every network interface, including the private network. With UFW active and only SSH allowed, the nodes cannot reach each other, so allow inter-node and CQL client traffic only from the other cluster nodes. Run the steps on all three Cassandra servers.

1. Allow SSH and enable UFW. Some server images already enable UFW, and the commands leave it active with the SSH rule in place. Enter `y` if UFW prompts for confirmation.

    ```console
    $ sudo ufw allow OpenSSH
    $ sudo ufw enable
    ```

1. Replace `PEER_IP` with the private IP address of one of the other two nodes, and allow inter-node traffic and CQL connections from it.

    ```console
    $ sudo ufw allow from PEER_IP to any port 7000 proto tcp comment 'cassandra gossip'
    $ sudo ufw allow from PEER_IP to any port 9042 proto tcp comment 'cassandra cql'
    ```

1. Run the two previous commands again with the private IP address of the remaining node. For example, the first node allows `NODE2_IP` and `NODE3_IP`.

1. Verify the firewall rules.

    ```console
    $ sudo ufw status
    ```

    The output lists rules that allow ports `7000` and `9042` from the private IP addresses of the other two nodes.

> [!NOTE]
> The JMX port `7199` that `nodetool` uses listens only on localhost and needs no firewall rule. A [network firewall](https://docs.vultr.com/products/network/firewall-groups/management/rules) from your hosting provider may filter only public traffic, so UFW is the control that applies to traffic on the private network.

## Start the Cluster

Nodes must join the cluster one at a time, because nodes that start at the same moment can cause token and bootstrap conflicts. Start the first node, wait for it to finish, and repeat on the second and third nodes.

1. Enable and start the Cassandra service on the first node.

    ```console
    $ sudo systemctl enable cassandra
    $ sudo systemctl start cassandra
    ```

1. Follow the system log until the startup completes.

    ```console
    $ sudo tail -f /var/log/cassandra/system.log | grep -E "Startup complete|listening for CQL|ERROR"
    ```

    Wait for a line that contains `Starting listening for CQL clients` with the private IP address of the node, followed by `Startup complete`. Press :key_ctrl: + :key_c: to stop following the log.

1. Check the status of the node.

    ```console
    $ nodetool status
    ```

    The output lists the node with the `UN` status, which means Up and Normal.

1. Verify the resource limits that the package applied to the Cassandra process.

    ```console
    $ cat /proc/$(pgrep -f CassandraDaemon)/limits
    ```

    The `Max open files` row displays the package limit of `100000`, and the `Max locked memory` row displays `unlimited`.

1. Repeat the previous four steps on the second node, and then on the third node. Start each node only after the previous node reports the `UN` status.

1. View the status of the cluster from any node.

    ```console
    $ nodetool status
    ```

    The output resembles the following:

    ```
    Datacenter: dc1
    ===============
    --  Address    Load       Tokens  Owns (effective)  Host ID   Rack
    UN  NODE1_IP   ...        16      ...               ...       rack1
    UN  NODE2_IP   ...        16      ...               ...       rack2
    UN  NODE3_IP   ...        16      ...               ...       rack3
    ```

1. Verify that all nodes agree on the cluster name and schema.

    ```console
    $ nodetool describecluster
    ```

    The `Name` field displays `Production Cassandra Cluster`, and the output lists one schema version that includes all three private IP addresses.

## Install the Client Tools

The first node acts as the client machine for `cqlsh`. The `cqlsh` version bundled with the package can fail on the Python version of recent Ubuntu releases, so install it in an isolated Python 3.11 environment with the `uv` package manager. Run the steps on the first node only.

1. Install `uv` and create a Python 3.11 virtual environment.

    ```console
    $ curl -LsSf https://astral.sh/uv/install.sh | sh
    $ ~/.local/bin/uv venv --python 3.11 ~/cassandra-client/venv
    ```

1. Install `cqlsh` and the Cassandra Python driver in the virtual environment.

    ```console
    $ CASS_DRIVER_NO_CYTHON=1 ~/.local/bin/uv pip install --python ~/cassandra-client/venv/bin/python cqlsh cassandra-driver
    ```

1. Add a shell alias for the installed `cqlsh`, and reload the shell configuration.

    ```console
    $ echo 'alias cqlsh="$HOME/cassandra-client/venv/bin/cqlsh"' >> ~/.bashrc
    $ source ~/.bashrc
    ```

1. Verify the `cqlsh` installation.

    ```console
    $ cqlsh --version
    ```

    The output displays the installed `cqlsh` version.

## Secure the Cluster

Cassandra stores roles in the `system_auth` keyspace and creates a default superuser named `cassandra` with the password `cassandra`, which anyone can guess. Replicate the system keyspaces to all three nodes, create your own superuser role, and disable the default role. Run the steps on the first node unless a step says otherwise.

1. Replace `NODE1_IP` with the private IP address of the first node, and connect as the default superuser. Enter `cassandra` when `cqlsh` prompts for the password.

    ```console
    $ cqlsh NODE1_IP -u cassandra
    ```

1. Replicate the authentication, distributed, and tracing system keyspaces to all three nodes.

    ```sql
    ALTER KEYSPACE system_auth WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
    ALTER KEYSPACE system_distributed WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
    ALTER KEYSPACE system_traces WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
    ```

1. Replace `DBA_USER` with a role name such as `dbadmin` and `DBA_PASSWORD` with a strong password, and create the administrative superuser role.

    ```sql
    CREATE ROLE DBA_USER WITH PASSWORD = 'DBA_PASSWORD' AND SUPERUSER = true AND LOGIN = true;
    EXIT;
    ```

1. Run a full repair of the three system keyspaces to copy their data to every replica. Run this command on each of the three nodes, one node at a time, and wait for it to finish before you start it on the next node.

    ```console
    $ for ks in system_auth system_distributed system_traces; do nodetool repair -full $ks; done
    ```

    Each repair ends with a line that reports that the repair command finished. Concurrent repairs on several nodes fail with an `Incremental repair session ... has failed` error, and Cassandra requires a full repair after a replication factor increase.

1. Connect to the first node as the new role. Enter `DBA_PASSWORD` when `cqlsh` prompts for the password.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER
    ```

1. Disable the default `cassandra` role, list the roles, and exit the CQL shell.

    ```sql
    ALTER ROLE cassandra WITH SUPERUSER = false AND LOGIN = false;
    LIST ROLES;
    EXIT;
    ```

    The `LIST ROLES` output displays `False` in the `super` and `login` columns for `cassandra`, and `True` in both columns for your new role.

Every later `cqlsh` command in this article connects with `-u DBA_USER` and prompts for `DBA_PASSWORD`.

## Verify the Deployment

Verify that the cluster replicates every row to all three nodes and keeps serving requests when one node fails.

### Verify Replication Across the Nodes

A keyspace with a replication factor of 3 stores every row on all three nodes. Create a test keyspace, write rows through the first node, and read them through the other two nodes.

1. Connect to the first node.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER
    ```

1. Create a `demo` keyspace with a replication factor of 3 and a `users` table, and insert two rows at the `LOCAL_QUORUM` consistency level.

    ```sql
    CREATE KEYSPACE demo WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
    CREATE TABLE demo.users (id uuid PRIMARY KEY, name text, email text);
    CONSISTENCY LOCAL_QUORUM;
    INSERT INTO demo.users (id, name, email) VALUES (uuid(), 'Alice', 'alice@example.com');
    INSERT INTO demo.users (id, name, email) VALUES (uuid(), 'Bob', 'bob@example.com');
    EXIT;
    ```

1. Read the rows through the second node.

    ```console
    $ cqlsh NODE2_IP -u DBA_USER -e "CONSISTENCY LOCAL_QUORUM; SELECT * FROM demo.users;"
    ```

    The output displays both rows.

1. Read the rows through the third node at the `ALL` consistency level, which succeeds only when all three replicas respond.

    ```console
    $ cqlsh NODE3_IP -u DBA_USER -e "CONSISTENCY ALL; SELECT * FROM demo.users;"
    ```

    The output displays both rows.

1. Replace `ROW_ID` with an `id` value from the previous output, and list the nodes that store that row.

    ```console
    $ nodetool getendpoints demo users ROW_ID
    ```

    The output lists all three private IP addresses.

### Test a Node Failure

With a replication factor of 3, `LOCAL_QUORUM` needs two replicas, so the cluster keeps serving requests when one node is down, while a read at the `ALL` consistency level fails. Write data while the third node is stopped, then confirm that the node receives the missed write after it returns.

1. Stop Cassandra on the third node.

    ```console
    $ sudo systemctl stop cassandra
    ```

1. Connect to the first node.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER
    ```

1. Insert and read a row at `LOCAL_QUORUM`.

    ```sql
    CONSISTENCY LOCAL_QUORUM;
    INSERT INTO demo.users (id, name, email) VALUES (uuid(), 'Carol', 'carol@example.com');
    SELECT * FROM demo.users;
    ```

    The output displays three rows.

1. Read the rows at `ALL`.

    ```sql
    CONSISTENCY ALL;
    SELECT * FROM demo.users;
    ```

    The query fails with an error that contains `Cannot achieve consistency level ALL`, because one replica is down. This result is expected.

1. Exit the CQL shell.

    ```sql
    EXIT;
    ```

1. Start Cassandra on the third node, and wait until `nodetool status` reports the `UN` status for it. The other nodes stored the missed write as a hint and replay it to the third node through hinted handoff.

    ```console
    $ sudo systemctl start cassandra
    ```

1. Verify on the first node that it replayed the hint to the third node.

    ```console
    $ sudo grep "Finished hinted handoff" /var/log/cassandra/system.log
    ```

    The output resembles the following:

    ```
    INFO  [HintsDispatcher:1] 2026-10-06T14:22:01,140 HintsDispatchExecutor.java:300 - Finished hinted handoff of file ...hints to endpoint /NODE3_IP:7000: ...
    ```

1. Read the rows from the first node at `ALL`.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER -e "CONSISTENCY ALL; SELECT * FROM demo.users;"
    ```

    The output displays all three rows, including `Carol`.

## Back Up the Cluster to Object Storage

S3-compatible object storage runs outside the private network. Each node uploads its backups over outbound HTTPS with the access key and secret key, so backups need no inbound firewall rule and the bucket stays private.

### Create the Backup Bucket

The `s3cmd` client manages buckets in S3-compatible storage. Install it on the first node and create a bucket for the backups.

1. Install `s3cmd`.

    ```console
    $ sudo apt install -y s3cmd
    ```

1. Create the `s3cmd` configuration file.

    ```console
    $ nano ~/s3.cfg
    ```

1. Add the following configuration:

    ```ini
    [default]
    access_key = ACCESS_KEY
    secret_key = SECRET_KEY
    host_base = OBJECT_STORAGE_HOSTNAME
    host_bucket = %(bucket)s.OBJECT_STORAGE_HOSTNAME
    use_https = True
    ```

    Save and close the file.

    Replace:

    * **ACCESS_KEY** and **SECRET_KEY**: The keys of your object storage service.
    * **OBJECT_STORAGE_HOSTNAME**: The endpoint hostname of your object storage service, in both places.

1. Restrict the file permissions to protect the keys.

    ```console
    $ chmod 600 ~/s3.cfg
    ```

1. Create the bucket. If the command reports that the name exists, choose a different name and use it in place of `cassandra-backups` in the later steps.

    ```console
    $ s3cmd -c ~/s3.cfg mb s3://cassandra-backups
    ```

    The output resembles the following:

    ```
    Bucket 's3://cassandra-backups/' created
    ```

### Install Medusa

Cassandra Medusa takes a snapshot of a node and uploads its SSTable files, the immutable data files that Cassandra writes to disk, to object storage. It connects to Cassandra with its own role and runs as root, because it reads the Cassandra data files.

1. Create the Medusa role. Run this command one time, on the first node. Replace `MEDUSA_PASSWORD` with a new password that does not contain the `%` character.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER -e "CREATE ROLE medusa WITH PASSWORD = 'MEDUSA_PASSWORD' AND LOGIN = true AND SUPERUSER = true;"
    ```

    The role is a superuser because Medusa does not document a least-privilege set of grants, and its `restore-cluster` command drops and recreates keyspaces, tables, and types across the cluster.

1. Install `uv` for all users. Run this step and the remaining steps of this section on all three nodes.

    ```console
    $ curl -LsSf https://astral.sh/uv/install.sh | sudo env UV_INSTALL_DIR=/usr/local/bin UV_NO_MODIFY_PATH=1 sh
    ```

1. Create a Python 3.11 virtual environment and install Medusa and `boto3` in it.

    ```console
    $ sudo env UV_PYTHON_INSTALL_DIR=/opt/uv-python uv venv --python 3.11 /opt/medusa
    $ sudo env UV_PYTHON_INSTALL_DIR=/opt/uv-python CASS_DRIVER_NO_CYTHON=1 uv pip install --python /opt/medusa/bin/python cassandra-medusa boto3
    ```

1. Link the `medusa` command into the system path.

    ```console
    $ sudo ln -sf /opt/medusa/bin/medusa /usr/local/bin/medusa
    ```

### Configure Medusa

Medusa reads the Object Storage keys from a credentials file and its settings from its own configuration file. Run the steps on all three nodes.

1. Create the Medusa configuration directory and the credentials file.

    ```console
    $ sudo mkdir -p /etc/medusa
    $ sudo nano /etc/medusa/credentials
    ```

1. Add the following content:

    ```ini
    [default]
    aws_access_key_id = ACCESS_KEY
    aws_secret_access_key = SECRET_KEY
    ```

    Save and close the file.

    Replace:

    * **ACCESS_KEY** and **SECRET_KEY**: The keys of your object storage service.

1. Display the private IP address of the node for the Medusa configuration.

    ```console
    $ awk '/^listen_address:/{print $2}' /etc/cassandra/cassandra.yaml
    ```

1. Create the Medusa configuration file.

    ```console
    $ sudo nano /etc/medusa/medusa.ini
    ```

1. Add the following configuration:

    ```ini
    [cassandra]
    config_file = /etc/cassandra/cassandra.yaml
    cql_username = medusa
    cql_password = MEDUSA_PASSWORD
    resolve_ip_addresses = False
    stop_cmd = /usr/bin/systemctl stop cassandra
    start_cmd = /usr/bin/systemctl start cassandra

    [storage]
    storage_provider = s3_compatible
    bucket_name = cassandra-backups
    key_file = /etc/medusa/credentials
    host = OBJECT_STORAGE_HOSTNAME
    port = 443
    secure = True
    ssl_verify = True
    region = default
    fqdn = NODE_PRIVATE_IP
    prefix = cassandra-cluster
    max_backup_count = 7
    transfer_max_bandwidth = 100MB/s
    concurrent_transfers = 2

    [logging]
    enabled = 1
    file = /var/log/medusa.log
    level = INFO
    ```

    Save and close the file.

    Replace:

    * **MEDUSA_PASSWORD**: The password of the `medusa` role.
    * **OBJECT_STORAGE_HOSTNAME**: The endpoint hostname of your object storage service.
    * **NODE_PRIVATE_IP**: The private IP address from the previous step.

    In the above configuration:

    * `stop_cmd` and `start_cmd`: The commands that Medusa runs to stop and start Cassandra during a restore.
    * `ssl_verify`: Verifies the TLS certificate of the object storage endpoint. Without it, Medusa connects over HTTPS without certificate checks.
    * `fqdn`: Identifies the node inside a backup.
    * `max_backup_count`: Keeps the seven most recent backups when `medusa purge` runs.
    * `transfer_max_bandwidth` and `concurrent_transfers`: Limit the upload rate of a backup.

1. Restrict both files to the root user.

    ```console
    $ sudo chmod 600 /etc/medusa/credentials /etc/medusa/medusa.ini
    ```

1. Verify that Medusa reaches the bucket.

    ```console
    $ sudo medusa list-backups
    ```

    On a new bucket, the command completes without an error and lists no backups.

### Run the First Backup

Medusa backs up one node per command, and a cluster backup consists of one node backup from every node under the same name. Run a full backup named `initial` on each node in turn.

1. Run a full backup on the first node, and wait for the command to finish.

    ```console
    $ sudo medusa backup-node --backup-name=initial --mode=full
    ```

1. Run the same command on the second node, wait for it to finish, and then run it on the third node.

1. List the backups after the third node finishes.

    ```console
    $ sudo medusa list-backups
    ```

    The output resembles the following:

    ```
    initial (started: 2026-10-06 14:31:49, finished: 2026-10-06 14:36:01)
    ```

    A backup that some nodes have not finished displays `finished: Incomplete [1 of 3 nodes finished]` instead.

1. Verify that every file of the backup is present and intact in object storage.

    ```console
    $ sudo medusa verify --backup-name=initial
    ```

    The output resembles the following:

    ```
    Validating initial ...
    - Completion: OK!
    - Manifest validated: OK!!
    ```

### Schedule Daily Backups

Backups run one node at a time, so each node gets its own start time. A shared date-based backup name groups the node backups of each day into one cluster backup.

1. Verify that all three nodes use the same time zone. Most cloud server images use UTC by default.

    ```console
    $ timedatectl
    ```

    The `Time zone` line displays the same value on every node.

1. Create the cron file on the first node.

    ```console
    $ sudo nano /etc/cron.d/medusa
    ```

1. Add the following entries:

    ```ini
    0 2 * * * root /usr/local/bin/medusa backup-node --backup-name=daily-$(date +\%Y\%m\%d) --mode=differential >> /var/log/medusa-cron.log 2>&1
    30 4 * * * root /usr/local/bin/medusa purge >> /var/log/medusa-cron.log 2>&1
    ```

    Save and close the file.

    In the above configuration:

    * `0 2 * * *`: Starts the backup at `02:00` UTC every day.
    * `--mode=differential`: Uploads only the SSTable files that changed since the previous backup.
    * `medusa purge`: Deletes the backups beyond `max_backup_count` at `04:30` UTC every day.

1. Set the permissions that cron requires for the file.

    ```console
    $ sudo chmod 644 /etc/cron.d/medusa
    ```

1. Repeat the previous three steps on the second and third nodes with backup start times of `20 2 * * *` and `40 2 * * *`.

### Restore a Node from a Backup

A restore replaces the data of a node with the files of a backup. Medusa stops Cassandra, downloads the files of the node, and starts Cassandra again. Run the following steps on the node that you restore, except where a step says otherwise.

> [!WARNING]
> A restore stops Cassandra on the node and replaces its existing data. Test a restore on a separate cluster before you rely on the backups.

1. Replace `BACKUP_NAME` with the name of a complete backup from `sudo medusa list-backups`, and restore the node.

    ```console
    $ sudo medusa restore-node --backup-name=BACKUP_NAME
    ```

1. Verify that the node returns to the `UN` status.

    ```console
    $ nodetool status
    ```

1. Run a full repair on the node to synchronize it with the other replicas.

    ```console
    $ nodetool repair -full
    ```

    The output ends with a line that reports that the repair command finished.

1. Verify from the first node that every replica, including the restored node, serves the test data.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER -e "CONSISTENCY ALL; SELECT * FROM demo.users;"
    ```

    The output displays the rows of the `demo.users` table.

To return the entire cluster to the state of a backup, use `medusa restore-cluster` instead. For more information, see the [Medusa documentation on restoring a full cluster](https://github.com/thelastpickle/cassandra-medusa/blob/master/docs/Restoring-a-full-cluster.md).

??? note "Monitor the Cluster with Prometheus and Grafana (Optional)"

    Prometheus collects Cassandra and server metrics from every node and evaluates alert rules, and Grafana displays them on a dashboard. Both run on the monitoring server, and you reach them through an SSH tunnel. Each node runs two exporters: the JMX exporter for Cassandra metrics and Node Exporter for server metrics.

    ### Prepare the Monitoring Server

    The monitoring server needs no Cassandra software, only network access to the nodes and the Grafana repository tools.

    1. Replace `MONITOR_PUBLIC_IP` with the public IP address of the monitoring server and `linuxuser` with your username, and connect with SSH keep-alive enabled.

        ```console
        $ ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=10 linuxuser@MONITOR_PUBLIC_IP
        ```

    1. List the IPv4 addresses of the network interfaces.

        ```console
        $ ip -4 -o addr show scope global | awk '{print $2, $4}'
        ```

        Note the address of the private network interface, which this article calls `MONITOR_IP`.

    1. Update the system and install the repository tools.

        ```console
        $ sudo apt update && sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y
        $ sudo apt install -y curl gnupg ca-certificates
        ```

    1. Verify that the monitoring server reaches the first node over the private network.

        ```console
        $ ping -c 3 NODE1_IP
        ```

        The output reports `0% packet loss`.

    1. Allow SSH and enable UFW so that the Grafana and Prometheus ports stay closed to the internet. Enter `y` if UFW prompts for confirmation.

        ```console
        $ sudo ufw allow OpenSSH
        $ sudo ufw enable
        ```

    ### Install the JMX Exporter

    The Prometheus JMX exporter runs inside the Cassandra process as a Java agent and publishes Cassandra metrics over HTTP. Run the steps on all three nodes, and finish them on one node before you start on the next.

    1. Download the JMX exporter Java agent.

        ```console
        $ sudo mkdir -p /opt/jmx_exporter
        $ sudo curl -fsSL -o /opt/jmx_exporter/jmx_prometheus_javaagent.jar \
            https://github.com/prometheus/jmx_exporter/releases/download/1.7.0/jmx_prometheus_javaagent-1.7.0.jar
        ```

    1. Create the exporter configuration file.

        ```console
        $ sudo nano /etc/cassandra/jmx_exporter.yml
        ```

    1. Add the following configuration:

        ```yaml
        lowercaseOutputName: true
        lowercaseOutputLabelNames: true
        includeObjectNames:
          - "org.apache.cassandra.metrics:type=ClientRequest,*"
          - "org.apache.cassandra.metrics:type=Storage,*"
          - "org.apache.cassandra.metrics:type=Compaction,*"
          - "org.apache.cassandra.metrics:type=DroppedMessage,*"
          - "org.apache.cassandra.metrics:type=CommitLog,*"
          - "java.lang:type=Memory"
        rules:
          - pattern: 'java.lang<type=Memory><HeapMemoryUsage>used'
            name: cassandra_jvm_heap_used_bytes
          - pattern: 'java.lang<type=Memory><HeapMemoryUsage>max'
            name: cassandra_jvm_heap_max_bytes
          - pattern: 'org.apache.cassandra.metrics<type=(\w+), scope=(\w+), name=(\w+)><>(Count|Value|50thPercentile|95thPercentile|99thPercentile|OneMinuteRate)'
            name: cassandra_$1_$3_$4
            labels:
              scope: "$2"
          - pattern: 'org.apache.cassandra.metrics<type=(\w+), name=(\w+)><>(Count|Value|OneMinuteRate)'
            name: cassandra_$1_$2_$3
        ```

        Save and close the file.

        In the above configuration:

        * `includeObjectNames`: Limits the export to cluster-level metric groups, which keeps each scrape fast.
        * `rules`: Convert the selected JMX attributes into metric names such as `cassandra_clientrequest_latency_99thpercentile`.

    1. Store the private IP address of the node in a shell variable, and back up the Cassandra environment file.

        ```console
        $ NODE_IP=$(awk '/^listen_address:/{print $2}' /etc/cassandra/cassandra.yaml)
        $ sudo cp /etc/cassandra/cassandra-env.sh /etc/cassandra/cassandra-env.sh.backup
        ```

    1. Append the Java agent option to the environment file, which binds the exporter to the private IP address of the node on port `7070`.

        ```console
        $ echo "JVM_OPTS=\"\$JVM_OPTS -javaagent:/opt/jmx_exporter/jmx_prometheus_javaagent.jar=$NODE_IP:7070:/etc/cassandra/jmx_exporter.yml\"" | sudo tee -a /etc/cassandra/cassandra-env.sh
        ```

    1. Flush the node to disk and restart Cassandra to load the agent.

        ```console
        $ nodetool drain
        $ sudo systemctl restart cassandra
        ```

    1. Wait until `nodetool status` reports the `UN` status for the node again. Restart only one node at a time, because `LOCAL_QUORUM` requests fail with two nodes down.

        ```console
        $ nodetool status
        ```

    1. Verify that the exporter serves Cassandra metrics.

        ```console
        $ curl -s http://$NODE_IP:7070/metrics | grep cassandra_clientrequest_latency_99thpercentile
        ```

        The output lists the 99th percentile latency metrics of the node. The client request metrics appear a few seconds after the node reports `UN`, when the `/var/log/cassandra/system.log` file shows `Startup complete`. If the output is empty, wait a few seconds and run the command again.

    ### Install Node Exporter

    Node Exporter publishes server metrics such as CPU, memory, and disk usage. Prometheus scrapes both exporters of every node, so each node allows the exporter ports from the monitoring server. Run the steps on all three nodes.

    1. Install Node Exporter and enable its service.

        ```console
        $ sudo apt install -y prometheus-node-exporter
        $ sudo systemctl enable --now prometheus-node-exporter
        ```

    1. Verify that Node Exporter serves metrics.

        ```console
        $ curl -s localhost:9100/metrics | head
        ```

        The output displays metric lines that begin with `# HELP` and `# TYPE`.

    1. Replace `MONITOR_IP` with the private IP address of the monitoring server, and allow both exporter ports from it.

        ```console
        $ sudo ufw allow from MONITOR_IP to any port 7070 proto tcp comment 'prometheus jmx exporter'
        $ sudo ufw allow from MONITOR_IP to any port 9100 proto tcp comment 'prometheus node exporter'
        ```

    1. Verify the firewall rules.

        ```console
        $ sudo ufw status
        ```

        The output lists rules that allow ports `7070` and `9100` from the monitoring server.

    ### Install and Configure Prometheus

    Prometheus scrapes the six exporter endpoints and evaluates alert rules against the collected metrics. Run the steps on the monitoring server.

    1. Install Prometheus.

        ```console
        $ sudo apt install -y prometheus
        ```

    1. Create the alert rules file.

        ```console
        $ sudo nano /etc/prometheus/cassandra-alerts.yml
        ```

    1. Add the following rules:

        ```yaml
        groups:
          - name: cassandra
            rules:
              - alert: CassandraNodeDown
                expr: up{job="cassandra"} == 0
                for: 1m
                labels: {severity: critical}
                annotations: {summary: "Cassandra on {{ $labels.instance }} is down"}
              - alert: CassandraHighReadLatency
                expr: cassandra_clientrequest_latency_99thpercentile{scope="Read"} / 1000 > 50
                for: 5m
                labels: {severity: warning}
                annotations: {summary: "p99 read latency above 50 ms on {{ $labels.instance }}"}
              - alert: CassandraHighWriteLatency
                expr: cassandra_clientrequest_latency_99thpercentile{scope="Write"} / 1000 > 50
                for: 5m
                labels: {severity: warning}
                annotations: {summary: "p99 write latency above 50 ms on {{ $labels.instance }}"}
              - alert: CassandraPendingCompactions
                expr: cassandra_compaction_pendingtasks_value > 100
                for: 15m
                labels: {severity: warning}
                annotations: {summary: "Compactions are falling behind on {{ $labels.instance }}"}
              - alert: CassandraHeapHigh
                expr: cassandra_jvm_heap_used_bytes / cassandra_jvm_heap_max_bytes > 0.85
                for: 10m
                labels: {severity: warning}
                annotations: {summary: "JVM heap above 85% on {{ $labels.instance }}"}
              - alert: DiskSpaceLow
                expr: node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} < 0.50
                for: 10m
                labels: {severity: warning}
                annotations: {summary: "Less than 50% disk free on {{ $labels.instance }}"}
        ```

        Save and close the file.

        Prometheus displays firing alerts on its **Alerts** page and sends no notifications with this configuration. To receive alerts by email or chat, configure [Prometheus Alertmanager](https://prometheus.io/docs/alerting/latest/alertmanager/).

    1. Open the Prometheus configuration file.

        ```console
        $ sudo nano /etc/prometheus/prometheus.yml
        ```

    1. Replace the contents of the file with the following configuration:

        ```yaml
        global:
          scrape_interval: 15s
          evaluation_interval: 15s

        rule_files:
          - /etc/prometheus/cassandra-alerts.yml

        scrape_configs:
          - job_name: cassandra
            static_configs:
              - targets: ['NODE1_IP:7070', 'NODE2_IP:7070', 'NODE3_IP:7070']
          - job_name: node
            static_configs:
              - targets: ['NODE1_IP:9100', 'NODE2_IP:9100', 'NODE3_IP:9100']
        ```

        Save and close the file.

        Replace:

        * **NODE1_IP**, **NODE2_IP**, and **NODE3_IP**: The private IP addresses of the three nodes.

    1. Validate the configuration.

        ```console
        $ promtool check config /etc/prometheus/prometheus.yml
        ```

        The output reports `SUCCESS` for the configuration file and for the rules file.

    1. Restart Prometheus to load the configuration.

        ```console
        $ sudo systemctl restart prometheus
        ```

    1. Verify that all six targets are up. Run this command about 30 seconds after the restart.

        ```console
        $ curl -s http://localhost:9090/api/v1/targets | grep -o '"health":"[a-z]*"' | sort | uniq -c
        ```

        The output resembles the following:

        ```
              6 "health":"up"
        ```

    ### Install and Configure Grafana

    Grafana reads the metrics from Prometheus and displays them on a provisioned dashboard. Run the steps on the monitoring server.

    1. Add the Grafana repository signing key and repository.

        ```console
        $ sudo mkdir -p /etc/apt/keyrings
        $ curl -fsSL https://apt.grafana.com/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/grafana.gpg
        $ echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee /etc/apt/sources.list.d/grafana.list
        ```

    1. Update the package index and install Grafana.

        ```console
        $ sudo apt update && sudo apt install -y grafana
        ```

    1. Create the data source provisioning file.

        ```console
        $ sudo nano /etc/grafana/provisioning/datasources/prometheus.yml
        ```

    1. Add the following configuration:

        ```yaml
        apiVersion: 1
        datasources:
          - name: Prometheus
            uid: prometheus
            type: prometheus
            url: http://localhost:9090
            isDefault: true
        ```

        Save and close the file.

    1. Create the dashboard directory and the dashboard provisioning file.

        ```console
        $ sudo mkdir -p /var/lib/grafana/dashboards
        $ sudo nano /etc/grafana/provisioning/dashboards/cassandra.yml
        ```

    1. Add the following configuration, which loads every dashboard in the directory into a Grafana folder named Cassandra:

        ```yaml
        apiVersion: 1
        providers:
          - name: cassandra
            folder: Cassandra
            type: file
            options:
              path: /var/lib/grafana/dashboards
        ```

        Save and close the file.

    1. Create the dashboard file.

        ```console
        $ sudo nano /var/lib/grafana/dashboards/cassandra-cluster.json
        ```

    1. Add the following dashboard definition:

        ```json
        {
          "title": "Cassandra Cluster",
          "uid": "cassandra-cluster",
          "refresh": "30s",
          "time": {"from": "now-1h", "to": "now"},
          "schemaVersion": 39,
          "panels": [
            {"id": 1, "type": "stat", "title": "Nodes up", "gridPos": {"x": 0, "y": 0, "w": 4, "h": 4},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "targets": [{"expr": "sum(up{job=\"cassandra\"})"}]},
            {"id": 2, "type": "stat", "title": "Pending compactions", "gridPos": {"x": 4, "y": 0, "w": 4, "h": 4},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "targets": [{"expr": "sum(cassandra_compaction_pendingtasks_value)"}]},
            {"id": 3, "type": "stat", "title": "Errors (timeouts + unavailables, last 5m)", "gridPos": {"x": 8, "y": 0, "w": 8, "h": 4},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "targets": [{"expr": "sum(increase(cassandra_clientrequest_timeouts_count[5m])) + sum(increase(cassandra_clientrequest_unavailables_count[5m]))"}]},
            {"id": 4, "type": "stat", "title": "Data per node", "gridPos": {"x": 16, "y": 0, "w": 8, "h": 4},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "fieldConfig": {"defaults": {"unit": "bytes"}},
             "targets": [{"expr": "cassandra_storage_load_count", "legendFormat": "{{instance}}"}]},
            {"id": 5, "type": "timeseries", "title": "Reads per second", "gridPos": {"x": 0, "y": 4, "w": 12, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "targets": [{"expr": "rate(cassandra_clientrequest_latency_count{scope=\"Read\"}[1m])", "legendFormat": "{{instance}}"}]},
            {"id": 6, "type": "timeseries", "title": "Writes per second", "gridPos": {"x": 12, "y": 4, "w": 12, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "targets": [{"expr": "rate(cassandra_clientrequest_latency_count{scope=\"Write\"}[1m])", "legendFormat": "{{instance}}"}]},
            {"id": 7, "type": "timeseries", "title": "p99 read latency", "gridPos": {"x": 0, "y": 12, "w": 12, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "fieldConfig": {"defaults": {"unit": "ms"}},
             "targets": [{"expr": "cassandra_clientrequest_latency_99thpercentile{scope=\"Read\"} / 1000", "legendFormat": "{{instance}}"}]},
            {"id": 8, "type": "timeseries", "title": "p99 write latency", "gridPos": {"x": 12, "y": 12, "w": 12, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "fieldConfig": {"defaults": {"unit": "ms"}},
             "targets": [{"expr": "cassandra_clientrequest_latency_99thpercentile{scope=\"Write\"} / 1000", "legendFormat": "{{instance}}"}]},
            {"id": 9, "type": "timeseries", "title": "CPU usage", "gridPos": {"x": 0, "y": 20, "w": 8, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "fieldConfig": {"defaults": {"unit": "percentunit", "max": 1}},
             "targets": [{"expr": "1 - avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[1m]))", "legendFormat": "{{instance}}"}]},
            {"id": 10, "type": "timeseries", "title": "JVM heap used", "gridPos": {"x": 8, "y": 20, "w": 8, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "fieldConfig": {"defaults": {"unit": "percentunit", "max": 1}},
             "targets": [{"expr": "cassandra_jvm_heap_used_bytes / cassandra_jvm_heap_max_bytes", "legendFormat": "{{instance}}"}]},
            {"id": 11, "type": "timeseries", "title": "Disk free", "gridPos": {"x": 16, "y": 20, "w": 8, "h": 8},
             "datasource": {"type": "prometheus", "uid": "prometheus"},
             "fieldConfig": {"defaults": {"unit": "percentunit", "max": 1}},
             "targets": [{"expr": "node_filesystem_avail_bytes{mountpoint=\"/\"} / node_filesystem_size_bytes{mountpoint=\"/\"}", "legendFormat": "{{instance}}"}]}
          ]
        }
        ```

        Save and close the file.

    1. Grant the `grafana` user ownership of the dashboard directory, and enable and start Grafana.

        ```console
        $ sudo chown -R grafana:grafana /var/lib/grafana/dashboards
        $ sudo systemctl enable --now grafana-server
        ```

    1. Verify that Grafana is running.

        ```console
        $ sudo systemctl status grafana-server
        ```

        The output displays `Active: active (running)`.

    ### Access the Grafana Dashboard

    UFW blocks the Grafana and Prometheus ports from the internet, so an SSH tunnel forwards them from your workstation to the monitoring server.

    1. Open an SSH tunnel from your workstation, and keep the session open.

        ```console
        $ ssh -L 3000:localhost:3000 -L 9090:localhost:9090 linuxuser@MONITOR_PUBLIC_IP
        ```

    1. Open `http://localhost:3000` in a web browser, and log in with the username `admin` and the password `admin`. Set a new password when Grafana prompts for one.

    1. Click **Dashboards**, open the **Cassandra** folder, and click **Cassandra Cluster**.

        ![Grafana dashboard named Cassandra Cluster. The stat panels display three nodes up, zero pending compactions, zero errors, and the data size of each node, above graphs of reads, writes, latency, CPU usage, JVM heap, and free disk space.](https://assets.vultrdevrel.com/docs-main-doc-assets-1/2695/4137cdde-cda0-47c2-82a8-00b369f7fd4f.png)

        The **Nodes up** panel displays `3` when Prometheus reaches the Cassandra exporter of every node.

    1. Open `http://localhost:9090` to view Prometheus. Navigate to **Status** > **Targets** to verify that all six targets report the `UP` state, and click **Alerts** to view the six alert rules.

## Migrate from Amazon Keyspaces to Apache Cassandra

Keyspaces implements the Cassandra CQL API, so a migration recreates each keyspace and table on the cluster, copies the rows, and changes the connection settings of each application while its CQL statements and driver stay the same. Run the steps on the first node, which holds the client tools and needs outbound internet access.

### Connect to Amazon Keyspaces

Keyspaces accepts only TLS connections, so `cqlsh` needs the Amazon root certificates and a separate configuration file that leaves the connection settings for your cluster unchanged. The certificate and configuration steps follow the [Amazon Keyspaces cqlsh TLS documentation](https://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.cqlsh.html#encrypt_using_tls).

1. Create a working directory for the migration files.

    ```console
    $ mkdir ~/keyspaces-migration && cd ~/keyspaces-migration
    ```

1. Download the Amazon root certificates and the Starfield root certificate, and combine them into one bundle.

    ```console
    $ curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
    $ curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
    $ curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
    $ curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
    $ curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
    $ cat AmazonRootCA1.pem AmazonRootCA2.pem AmazonRootCA3.pem AmazonRootCA4.pem sf-class2-root.crt > keyspaces-bundle.pem
    ```

1. Create a `cqlsh` configuration file for Keyspaces.

    ```console
    $ nano ~/keyspaces-migration/cqlshrc
    ```

1. Add the following configuration:

    ```ini
    [ssl]
    validate = true
    certfile = ~/keyspaces-migration/keyspaces-bundle.pem
    ```

    Save and close the file.

1. Replace `REGION` with the AWS Region of your tables and `SERVICE_USER` with the service-specific user name, and list the Keyspaces keyspaces over TLS on port `9142`. Enter `SERVICE_PASSWORD` when `cqlsh` prompts for the password.

    ```console
    $ cqlsh --cqlshrc ~/keyspaces-migration/cqlshrc cassandra.REGION.amazonaws.com 9142 -u SERVICE_USER --ssl \
        -e "SELECT keyspace_name FROM system_schema.keyspaces;"
    ```

    The output includes `KEYSPACE_NAME`.

### Migrate the Schema

The `cqlsh` client from Cassandra 4.0 and later runs `DESCRIBE` on the server, and Keyspaces reports Cassandra 3.11, so `DESCRIBE` does not work against Keyspaces. The Cassandra Python driver reads the schema tables directly and generates the `CREATE` statements instead.

1. Create the schema export script.

    ```console
    $ nano ~/keyspaces-migration/export_schema.py
    ```

1. Add the following code:

    ```python
    import getpass
    import sys
    from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED

    from cassandra.auth import PlainTextAuthProvider
    from cassandra.cluster import Cluster

    region, keyspace, user = sys.argv[1:4]
    password = getpass.getpass("Service password: ")

    ssl_context = SSLContext(PROTOCOL_TLSv1_2)
    ssl_context.load_verify_locations("keyspaces-bundle.pem")
    ssl_context.verify_mode = CERT_REQUIRED

    cluster = Cluster(
        [f"cassandra.{region}.amazonaws.com"],
        port=9142,
        ssl_context=ssl_context,
        auth_provider=PlainTextAuthProvider(username=user, password=password),
    )
    cluster.connect()
    print(cluster.metadata.keyspaces[keyspace].export_as_string())
    cluster.shutdown()
    ```

    Save and close the file.

    The script connects with the service-specific credentials over TLS and prints the `CREATE` statements for the keyspace, its user-defined types, and its tables.

1. Export the schema of the keyspace to a file. Enter `SERVICE_PASSWORD` when the script prompts for it.

    ```console
    $ ~/cassandra-client/venv/bin/python export_schema.py REGION KEYSPACE_NAME SERVICE_USER > schema.cql
    ```

1. Open the exported schema.

    ```console
    $ nano schema.cql
    ```

1. Adapt the statements for Cassandra 5.0, then save and close the file:

    * **Replication:** Replace `{'class': 'SingleRegionStrategy'}` with `{'class': 'NetworkTopologyStrategy', 'dc1': '3'}` in the `CREATE KEYSPACE` statement.
    * **Table options:** Keep the column definitions, the primary key, and the `CLUSTERING ORDER BY` and `default_time_to_live` options. Delete every other `WITH` and `AND` option, including `read_repair_chance` and `dclocal_read_repair_chance`, which Cassandra 5.0 rejects. The tables then use the compaction, compression, and caching defaults of the cluster.
    * **Keyspaces-only settings:** Capacity mode, point-in-time recovery, AWS KMS keys, and tags have no Cassandra equivalent and do not appear in the CQL schema.

1. Create the schema on the cluster.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER -f schema.cql
    ```

1. Verify the keyspace on the cluster.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER -e "DESCRIBE KEYSPACE KEYSPACE_NAME;"
    ```

    The output displays `NetworkTopologyStrategy` with `'dc1': '3'` and every table of the keyspace.

### Migrate the Data

The `cqlsh` `COPY TO` command exports a table from Keyspaces to a CSV file, and `COPY FROM` imports the file into the cluster. Both commands run at the consistency level of the `cqlsh` session, so set `LOCAL_QUORUM` on each side. Repeat the steps for each table.

1. Export the table from Keyspaces at `LOCAL_QUORUM`. Enter `SERVICE_PASSWORD` when prompted.

    ```console
    $ cqlsh --cqlshrc ~/keyspaces-migration/cqlshrc cassandra.REGION.amazonaws.com 9142 -u SERVICE_USER --ssl \
        -e "CONSISTENCY LOCAL_QUORUM; COPY KEYSPACE_NAME.TABLE_NAME TO 'TABLE_NAME.csv' WITH HEADER = true;"
    ```

    The command reports the number of rows that it exported. An export reads every row of the table, so raise the read capacity of a table in provisioned capacity mode before the export to avoid throttling.

1. Import the file into the cluster at `LOCAL_QUORUM`.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER \
        -e "CONSISTENCY LOCAL_QUORUM; COPY KEYSPACE_NAME.TABLE_NAME FROM 'TABLE_NAME.csv' WITH HEADER = true;"
    ```

    The command reports the number of rows that it imported.

1. Count the rows of the table on the cluster.

    ```console
    $ cqlsh NODE1_IP -u DBA_USER -e "CONSISTENCY LOCAL_QUORUM; SELECT COUNT(*) FROM KEYSPACE_NAME.TABLE_NAME;"
    ```

    The count matches the number of rows that `COPY TO` exported and `COPY FROM` imported. For tables with millions of rows, `COUNT(*)` can time out, so compare the `COPY` totals and a sample of rows read by primary key on both sides instead.

`COPY` copies column values only, so imported rows receive new write timestamps and lose their per-cell `TTL` values. For tables that use `TTL` values or that keep receiving writes, use the [DataStax Bulk Loader (DSBulk)](https://github.com/datastax/dsbulk) with `--schema.preserveTimestamp true` and `--schema.preserveTtl true`, which unloads and loads each column with its `WRITETIME` and `TTL`, and which also parallelizes large tables.

### Migrate Applications

Each application keeps its CQL statements and driver and changes only its connection settings:

* **Contact points:** Replace `cassandra.REGION.amazonaws.com` on port `9142` with the private IP addresses of the three nodes on port `9042`. Run the application in the same private network, and allow its private IP address on port `9042` in UFW on each node.
* **Authentication:** Replace the SigV4 plugin or the service-specific credentials with a CQL role through the plain-text authentication provider of the driver. During the dual-write period only, keep a separate driver session that connects to Keyspaces with the SigV4 plugin, and remove that session and the plugin after the write cutover.
* **TLS:** Remove the Keyspaces certificate settings. Add TLS settings only after you enable `client_encryption_options` on the nodes.
* **Local datacenter:** Replace the AWS Region name with `dc1`. A driver sends requests only to nodes in its local datacenter, so a Region name leaves the application with no nodes to use.
* **Consistency level:** Set the default consistency level of the driver to `LOCAL_QUORUM`.

In the DataStax Java driver, these settings are `basic.contact-points`, `advanced.auth-provider`, `advanced.ssl-engine-factory`, `basic.load-balancing-policy.local-datacenter`, and `basic.request.consistency`.

### Migrate Access Control

Translate the IAM policies that grant access to Keyspaces into CQL roles and permissions:

* **Actions:** `cassandra:Select` becomes `SELECT`, `cassandra:Modify` becomes `MODIFY`, and `cassandra:Create`, `cassandra:Alter`, and `cassandra:Drop` become `CREATE`, `ALTER`, and `DROP`.
* **Resources:** A policy for every table in a keyspace becomes a grant `ON KEYSPACE`, and a policy for one table becomes a grant `ON TABLE`.
* **Principals:** Each IAM user or role that an application uses becomes a CQL login role, created with `CREATE ROLE` and checked with `LIST ALL PERMISSIONS OF`. Use the `DBA_USER` role only for administration.
* **Conditions:** Tag-based IAM conditions have no CQL equivalent, so grant those permissions on the keyspace or the table.
* **Restores:** `cassandra:Restore` has no CQL permission. Medusa restores run on the nodes with `sudo`.

### Cut Over Tables That Receive Writes

Tables that keep receiving writes during the migration need a dual-write period so no update is lost:

* **Dual writes:** Configure each application to write to both Keyspaces and the cluster, with retries for partial failures. Reconcile deletes explicitly, and pause writes during final reconciliation if your process cannot resolve concurrent changes.
* **Backfill:** Copy the existing rows with DSBulk and preserved write timestamps, so backfilled values never overwrite newer application writes. Validate row counts and sample records before you move reads.
* **Read cutover:** Move the reads of the application to the cluster, and watch the latency and error panels of the Grafana dashboard.
* **Write cutover:** Stop the writes to Keyspaces after the cluster serves all reads without errors for a period that you agree on in advance. Keep the Keyspaces tables, with point-in-time recovery enabled, until the first Medusa backups of the migrated data complete.
* **Rollback:** Before the write cutover, reads can return to Keyspaces. After the write cutover, replay the changes made on the cluster to Keyspaces before you return reads to it.

### Migration Considerations

The following items require attention during the migration:

* **Repairs:** Run `nodetool repair` on every node at least one time within the `gc_grace_seconds` period of your tables, 10 days by default, so deleted data does not reappear. Schedule repairs with cron or with [Cassandra Reaper](https://cassandra-reaper.io/).
* **Recovery point:** Schedule Medusa backups more often than daily if you need a shorter recovery point.
* **Lightweight transactions:** Conditional statements such as `INSERT ... IF NOT EXISTS` use the Paxos protocol and take longer than regular writes.
* **Batches:** Keyspaces limits a logged batch to 100 statements and an unlogged batch to 30. Cassandra limits batches by size with `batch_size_warn_threshold` and `batch_size_fail_threshold`.
* **Change data capture:** Keyspaces delivers change records through its streams API. Cassandra change data capture keeps commit log segments for a consumer that you run, and this article does not configure it.
* **Cost model:** Keyspaces charges for requests and storage, or for provisioned capacity. The cluster costs the price of its four servers and the object storage, regardless of request volume.

## Troubleshoot Common Issues

Most problems come from leftover default data, blocked ports, or wrong addresses or credentials. The following table lists common symptoms with their cause and resolution.

| Symptom | Cause | Resolution |
|---|---|---|
| The log contains `Saved cluster name Test Cluster != configured name`, or `nodetool status` displays `127.0.0.1`. | The Cassandra instance that the package started at install time is still running or left its data behind. | Run `sudo pkill -f CassandraDaemon`, confirm with `pgrep -f CassandraDaemon`, run the `find` command from [Remove the Default Single-Node Data](#remove-the-default-single-node-data), and start Cassandra again. |
| A node never reaches the `UN` status. | UFW blocks inter-node traffic on port `7000`. | Repeat the firewall steps, and test the connection with `nc -zv PEER_IP 7000`. |
| The nodes form separate one-node clusters. | The nodes use public IP addresses, different seed lists, or different datacenter names. | Use the private IP addresses, the same seed list, and `dc=dc1` on every node. |
| `s3cmd` or `medusa list-backups` fails with an access error. | The hostname or the keys are wrong. | Check the `~/s3.cfg` and `/etc/medusa/credentials` files. |
| Medusa reports a Cassandra authentication error. | The `medusa` role is missing, or its password differs from `cql_password`. | Confirm that the role exists and that `cql_password` in the `/etc/medusa/medusa.ini` file matches it. |
| A backup stays `Incomplete`. | One node did not finish its backup. | Run `sudo medusa backup-node --backup-name=BACKUP_NAME` on the missing node, and check it with `sudo medusa status --backup-name=BACKUP_NAME`. |
| Cassandra does not start after you add the JMX exporter. | The Java agent option in the environment file is wrong. | Restore the `/etc/cassandra/cassandra-env.sh.backup` file, restart Cassandra, and check the `/var/log/cassandra/system.log` file. |
| A Prometheus target reports `DOWN`. | UFW blocks the exporter port, or the exporter is not running. | Check UFW on that node, and run `curl http://NODE_PRIVATE_IP:7070/metrics` from the monitoring server. |
| An application reports that no hosts are available. | The driver still uses the AWS Region name as its local datacenter. | Set the local datacenter to `dc1`. |

The following commands display the state of a node and its tables:

* `nodetool status`: Lists the state of every node.
* `nodetool describecluster`: Displays the cluster name and schema agreement.
* `nodetool tablestats -H KEYSPACE_NAME.TABLE_NAME`: Displays the size, SSTable count, and latencies of a table.
* `nodetool compactionstats`: Lists the pending compactions.
* `sudo tail -f /var/log/cassandra/system.log`: Follows the Cassandra system log.
* `sudo tail -f /var/log/medusa.log`: Follows the Medusa log.

## Conclusion

You have successfully deployed a three-node Apache Cassandra 5.0 cluster as an alternative to Amazon Keyspaces. The cluster replicates every row across three racks, uses a dedicated superuser role in place of the default `cassandra` role, keeps serving `LOCAL_QUORUM` requests when one node fails, and uploads daily backups to S3-compatible object storage. To add capacity, add three nodes at a time, one per rack, and to move existing tables and applications, follow [Migrate from Amazon Keyspaces to Apache Cassandra](#migrate-from-amazon-keyspaces-to-apache-cassandra). For more information, see the [production recommendations in the Apache Cassandra documentation](https://cassandra.apache.org/doc/stable/cassandra/getting-started/production.html).
