Search code examples
c#asp.netcassandradatastax-csharp-driver

Can I have two Cassandra Sessions in C# backend application?


I need to talk to two Cassandra clusters in my backend at stable environment. However, in beta I have only one cluster and it's config is duplicated, so during startup we create two sessions. Is it ok to have two sessions for one cluster?

Also we have multiple keyspaces, but only one connection for them. Should I make new session for each keyspace?

I see that session should be singleton, but I think it's not a demand, but a recommendation.


Solution

  • The recommendation to only create and reuse a single session per application is because session creation is very expensive.

    Each time a session is created, the driver has to go through its standard initialisation process and open connection pools to every node in the cluster. Apart from the significant increase in memory usage, this will slow down your application for no benefit.

    It makes no sense to create a session for each keyspace since the session can handle thousands of requests concurrently. All you need to do is to specify the keyspace when referring to a table in the query, for example:

    SELECT ... FROM keyspace_name.table_name WHERE ...
    

    As you pointed out, there is no technical barrier that prevents your application from creating multiple sessions. But there is also no benefit to doing so, just a lot of disadvantages so we don't recommend it. Cheers!