
Amazon 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 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.
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.
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.
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.Before you begin:
ServerAliveInterval SSH option enabled, and run long commands, such as package upgrades, inside a tmux session.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.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.
Update the package index and upgrade the installed packages.
Install the repository tools and the OpenJDK 17 runtime.
Set Java 17 as the default Java runtime.
Verify the active Java version.
The first line of the output begins with openjdk version "17.
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.
Download the Apache Cassandra repository signing keys.
Add the Cassandra 5.0 repository to the APT sources.
Update the package index and install Cassandra.
Verify the installed Cassandra version.
The output displays a version in the 5.0 series.
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.
Stop the Cassandra service.
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.
Verify that no Cassandra process is running.
The command prints no output. If it prints a process ID, wait a few seconds and run it again.
Delete the default data, commit log, saved caches, and hints.
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.
Verify that the data directory is empty.
The command prints no output.
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.
Increase the maximum number of memory-mapped areas.
Apply the kernel setting.
The output displays vm.max_map_count = 1048575.
Disable swap, and comment out the swap entries in the /etc/fstab file to keep swap disabled after a reboot.
Verify that swap is disabled.
The swapon command prints no output, and the Swap row of the free output displays 0B.
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.
Back up the default configuration file.
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.
Set the cluster name, which must be the same on every node.
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.
Bind inter-node and client traffic to the private IP address.
Set the snitch to GossipingPropertyFileSnitch, which reads the datacenter and rack of each node from a properties file.
Enable password authentication and role-based authorization.
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.
Verify the settings in the configuration file.
The output on the first node resembles the following, with your private IP addresses in place of the placeholders:
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.
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.
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.
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.
Verify the firewall rules.
The output lists rules that allow ports 7000 and 9042 from the private IP addresses of the other two nodes.
The JMX port 7199 that nodetool uses listens only on localhost and needs no firewall rule. A network firewall from your hosting provider may filter only public traffic, so UFW is the control that applies to traffic on the private network.
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.
Enable and start the Cassandra service on the first node.
Follow the system log until the startup completes.
Wait for a line that contains Starting listening for CQL clients with the private IP address of the node, followed by Startup complete. Press Ctrl + C to stop following the log.
Check the status of the node.
The output lists the node with the UN status, which means Up and Normal.
Verify the resource limits that the package applied to the Cassandra process.
The Max open files row displays the package limit of 100000, and the Max locked memory row displays unlimited.
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.
View the status of the cluster from any node.
The output resembles the following:
Verify that all nodes agree on the cluster name and schema.
The Name field displays Production Cassandra Cluster, and the output lists one schema version that includes all three private IP addresses.
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.
Install uv and create a Python 3.11 virtual environment.
Install cqlsh and the Cassandra Python driver in the virtual environment.
Add a shell alias for the installed cqlsh, and reload the shell configuration.
Verify the cqlsh installation.
The output displays the installed cqlsh version.
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.
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.
Replicate the authentication, distributed, and tracing system keyspaces to all three nodes.
Replace DBA_USER with a role name such as dbadmin and DBA_PASSWORD with a strong password, and create the administrative superuser role.
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.
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.
Connect to the first node as the new role. Enter DBA_PASSWORD when cqlsh prompts for the password.
Disable the default cassandra role, list the roles, and exit the CQL shell.
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 that the cluster replicates every row to all three nodes and keeps serving requests when one node fails.
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.
Connect to the first node.
Create a demo keyspace with a replication factor of 3 and a users table, and insert two rows at the LOCAL_QUORUM consistency level.
Read the rows through the second node.
The output displays both rows.
Read the rows through the third node at the ALL consistency level, which succeeds only when all three replicas respond.
The output displays both rows.
Replace ROW_ID with an id value from the previous output, and list the nodes that store that row.
The output lists all three private IP addresses.
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.
Stop Cassandra on the third node.
Connect to the first node.
Insert and read a row at LOCAL_QUORUM.
The output displays three rows.
Read the rows at ALL.
The query fails with an error that contains Cannot achieve consistency level ALL, because one replica is down. This result is expected.
Exit the CQL shell.
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.
Verify on the first node that it replayed the hint to the third node.
The output resembles the following:
Read the rows from the first node at ALL.
The output displays all three rows, including Carol.
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.
The s3cmd client manages buckets in S3-compatible storage. Install it on the first node and create a bucket for the backups.
Install s3cmd.
Create the s3cmd configuration file.
Add the following configuration:
Save and close the file.
Replace:
Restrict the file permissions to protect the keys.
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.
The output resembles the following:
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.
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.
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.
Install uv for all users. Run this step and the remaining steps of this section on all three nodes.
Create a Python 3.11 virtual environment and install Medusa and boto3 in it.
Link the medusa command into the system path.
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.
Create the Medusa configuration directory and the credentials file.
Add the following content:
Save and close the file.
Replace:
Display the private IP address of the node for the Medusa configuration.
Create the Medusa configuration file.
Add the following configuration:
Save and close the file.
Replace:
medusa role.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.Restrict both files to the root user.
Verify that Medusa reaches the bucket.
On a new bucket, the command completes without an error and lists no backups.
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.
Run a full backup on the first node, and wait for the command to finish.
Run the same command on the second node, wait for it to finish, and then run it on the third node.
List the backups after the third node finishes.
The output resembles the following:
A backup that some nodes have not finished displays finished: Incomplete [1 of 3 nodes finished] instead.
Verify that every file of the backup is present and intact in object storage.
The output resembles the following:
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.
Verify that all three nodes use the same time zone. Most cloud server images use UTC by default.
The Time zone line displays the same value on every node.
Create the cron file on the first node.
Add the following entries:
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.Set the permissions that cron requires for the file.
Repeat the previous three steps on the second and third nodes with backup start times of 20 2 * * * and 40 2 * * *.
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.
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.
Replace BACKUP_NAME with the name of a complete backup from sudo medusa list-backups, and restore the node.
Verify that the node returns to the UN status.
Run a full repair on the node to synchronize it with the other replicas.
The output ends with a line that reports that the repair command finished.
Verify from the first node that every replica, including the restored node, serves the test data.
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.
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.
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.
Create a working directory for the migration files.
Download the Amazon root certificates and the Starfield root certificate, and combine them into one bundle.
Create a cqlsh configuration file for Keyspaces.
Add the following configuration:
Save and close the file.
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.
The output includes KEYSPACE_NAME.
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.
Create the schema export script.
Add the following code:
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.
Export the schema of the keyspace to a file. Enter SERVICE_PASSWORD when the script prompts for it.
Open the exported schema.
Adapt the statements for Cassandra 5.0, then save and close the file:
{'class': 'SingleRegionStrategy'} with {'class': 'NetworkTopologyStrategy', 'dc1': '3'} in the CREATE KEYSPACE statement.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.Create the schema on the cluster.
Verify the keyspace on the cluster.
The output displays NetworkTopologyStrategy with 'dc1': '3' and every table of the keyspace.
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.
Export the table from Keyspaces at LOCAL_QUORUM. Enter SERVICE_PASSWORD when prompted.
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.
Import the file into the cluster at LOCAL_QUORUM.
The command reports the number of rows that it imported.
Count the rows of the table on the cluster.
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) 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.
Each application keeps its CQL statements and driver and changes only its connection settings:
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.client_encryption_options on the nodes.dc1. A driver sends requests only to nodes in its local datacenter, so a Region name leaves the application with no nodes to use.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.
Translate the IAM policies that grant access to Keyspaces into CQL roles and permissions:
cassandra:Select becomes SELECT, cassandra:Modify becomes MODIFY, and cassandra:Create, cassandra:Alter, and cassandra:Drop become CREATE, ALTER, and DROP.ON KEYSPACE, and a policy for one table becomes a grant ON TABLE.CREATE ROLE and checked with LIST ALL PERMISSIONS OF. Use the DBA_USER role only for administration.cassandra:Restore has no CQL permission. Medusa restores run on the nodes with sudo.Tables that keep receiving writes during the migration need a dual-write period so no update is lost:
The following items require attention during the migration:
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.INSERT ... IF NOT EXISTS use the Paxos protocol and take longer than regular writes.batch_size_warn_threshold and batch_size_fail_threshold.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.
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.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. For more information, see the production recommendations in the Apache Cassandra documentation.
0 Comments
Be the first to comment and share your perspective with the community.