Search code examples
postgresqlscalaakka-streamakka-http

PSQLException: FATAL: sorry, too many clients already Akka HTTP


I have an application with a connection to PostgreSQL database, API and Akka stream usage to extract tweets using Twitter4J. Extracted tweets are written to the database and then they are queried using Slick. Using Akka HTTP I have created an API to send queries to db. So my problem is that after a few requests I get this error:

enter image description here

I am not sure where is the problem and why it is happening as I am closing Actor system on complete.

object Main extends ApiRoute {

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher
    val twitterStream = TwitterStreamFilters.configureTwitterStream()
    val counter = new Counter
    twitterStream.addListener(counter)
    val bindingFuture = Http().bindAndHandle(routes, "localhost", 8080)
    println("Server started!")
    StdIn.readLine()
    bindingFuture
      .flatMap(_.unbind())
      .onComplete(_ => system.terminate())
  } 

And application.conf file:

scalaxdb = {
  dataSourceClass = "slick.jdbc.DatabaseUrlDataSource"
  properties = {
    driver = "org.postgresql.Driver"
    url = "jdbc:postgresql://localhost/twitter2.0?user=user&password=password"
  }
}

I would be grateful for any help!


Solution

  • Can you try the following configuration?

    scalaxdb = {
      dataSourceClass = "slick.jdbc.DatabaseUrlDataSource"
      properties = {
        driver = "org.postgresql.Driver"
        url = "jdbc:postgresql://localhost/twitter2.0?user=user&password=password"
      }
      numThreads = 10
    }
    

    So with the numThreads, I'm limiting my connections to 10.

    You should also probably show the code where you do the communication with the database?