Pablo Yabo
Pablo Yabo

Reputation: 2813

Cassandra connections best practice

I'm using Node JS with Cassandra and I wonder what the best way to interact. I have multiple modules that interact with Cassandra and I want to know if it's better to

  1. keep a single connection for all the modules
  2. set a connection for each module, or if the best is to;
  3. connect to Cassandra each time I have a request.

This web application uses Cassandra for most of the requests.

Upvotes: 4

Views: 2531

Answers (2)

jorgebg
jorgebg

Reputation: 6600

I would recommend you to use the DataStax Node.js driver for Cassandra, it features connection pooling and transparent failover, you only need to execute your queries and it will handle the rest for you.

var cassandra = require('cassandra-driver');
var client = new cassandra.Client({
  contactPoints: ['host1', 'host2'], 
  keyspace: 'ks1'
});
var query = 'SELECT email, last_name FROM user_profiles WHERE key=?';
//the driver will handle connection pool and failover
client.execute(query, ['guy'], function(err, result) {
  assert.ifError(err);
  console.log('User profile email ' + result.rows[0].email);
});

Disclaimer: I'm an active developer of the project

Upvotes: 2

Lyuben Todorov
Lyuben Todorov

Reputation: 14173

I'd pool connections and recycle them rather than going with one of the options you listed. That way you don't need to destroy already created connections. The only thing I'd be weary of is having too large a pool, so make sure you set a sensible threshold.

Something like this:

no connections are available in pool
  create connection (add it back once finished using it)
connections are available in pool
  fetch connection from pool

Reasons for choosing a pool rather than a hardcoded number:

  1. keep a single connection for all the modules - This will be a bottleneck unless you are running a single threaded app and you aren't
  2. set a connection for each module - You need to provide us with more context. This might a good approach based on how threaded each module is.
  3. connect to Cassandra each time I have a request - Building connections isn't cheap (code below), so don't discard them!

.

Cluster cluster = Cluster.builder().addContactPoints("localhost").build();
long start = System.currentTimeMillis();
Session session = cluster.connect();
System.out.println(String.format("Took %s ms", System.currentTimeMillis() - start));

Output: 490 ms.

Upvotes: 2

Related Questions