Replication: Keeping Copies of Your Data

You have written a lot of CQL. The lessons in this last section look at what happens to your data inside the cluster. First: the copies.

Replication factor

When you create a keyspace, you choose how many copies of the data to keep:

CREATE KEYSPACE shop
WITH replication = {
  'class': 'SimpleStrategy',
  'replication_factor': 3
};

The replication factor (RF) is the number of nodes that hold a copy of each row. With RF 3, every row is stored on three nodes:

     write a row with key 'alice'
                |
                v   (the token points to Node B)
   +--------+--------+--------+--------+
   | Node A | Node B | Node C | Node D |
   +--------+--------+--------+--------+
              copy 1   copy 2   copy 3

The token of the partition key picks the node for the first copy. The other copies go to the next nodes around the ring.

Now if Node C stops working, every row it held is still on two other nodes. Your app can keep reading and writing. This is why RF 3 is a common choice for real clusters.

You can see the settings of the keyspace you are working in with DESCRIBE KEYSPACE:

DESCRIBE KEYSPACE;

Output:

CREATE KEYSPACE sandbox_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}  AND durable_writes = true;

Our practice keyspace keeps just 1 copy, which is enough for learning. A real cluster would use 3.

Replication strategies

The 'class' setting is the replication strategy. It decides where the copies go.

  • SimpleStrategy places the copies on the next nodes around the ring. It is fine for learning and for a cluster in one data center.
  • NetworkTopologyStrategy is the one to use in production. It knows about data centers (groups of nodes in one location), so you can set the number of copies for each one:
CREATE KEYSPACE shop
WITH replication = {
  'class': 'NetworkTopologyStrategy',
  'us_east': 3,
  'eu_west': 3
};

Here every row has 3 copies in the US and 3 in Europe. If one whole data center goes offline, the other still has all the data. Users in each region can also read from the data center close to them.

Replication is set once per keyspace. After that, Cassandra makes the copies for you on every write.

Replication is not a backup, though. If you delete a row, the delete is copied to every node too.

If there are 3 copies, how many of them must answer before a read or write is done? The next lesson answers that.

In the exercise, check what the replication factor means.