Reusing Alpakka Database Session

This example is specific to Alpakka Cassandra, but in principle it applies to other databases as well.

How can I reuse the same database session, created with Cluster.builder....connect() across multiple actors?

I can’t simply encapsulate the session in an actor, because some functionality that the session provides is not in request-response format.

Here is a skeleton example:

def receive = { 
    case Message =>
        // needs session
        val preparedStatement = session.prepare("...")
        val flow = CassandraFlow.createUnloggedBatchWithPassThrough[...](...)
        source.via(flow).runWith(Sink.seq) pipeTo sender
}

How can I avoid re-creating a session, i.e. a Connection Pool, within every actor?

Distributing the session object to all actors which need it also seems like a problem since the session is not serializable.

Ok guys, I think I have come up with a pretty good solution. I have all my Message case classes inherit from the following trait:

  trait DatabaseOperation {
    def apply()(implicit session: Session, materializer: Materializer): Unit
  }

The actor that wraps the database receives DatabaseOperations and then calls the apply method on them, thereby passing in the session. The actual logic lives in the case class, i.e. the message, which receives the database connection. This way I am still 100% flexible to do anything I want with the database from anywhere I want by creating DatabaseOperation case classes, while messages remain serializable.

Let me know what you think!