# Reusing Alpakka Database Session

**URL:** <https://discuss.akka.io/t/reusing-alpakka-database-session/4697>\
**Category:** Akka Streams & Alpakka\
**Created:** [July 25, 2019, 3:06am UTC](https://discuss.akka.io/t/reusing-alpakka-database-session/4697 "2019-07-25T03:06:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ignatius](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/ignatius/32/1787_2.png) [@ignatius](https://discuss.akka.io/u/ignatius)\
**Post date:** [July 25, 2019, 3:06am UTC](https://discuss.akka.io/t/reusing-alpakka-database-session/4697/1 "2019-07-25T03:06:04Z")

</div>

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:

```scala
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.

---

<div class="post-metadata">

**Author:** ![ignatius](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/ignatius/32/1787_2.png) [@ignatius](https://discuss.akka.io/u/ignatius)\
**Post date:** [July 25, 2019, 6:02am UTC](https://discuss.akka.io/t/reusing-alpakka-database-session/4697/2 "2019-07-25T06:02:16Z")

</div>

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:

```auto
  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!
