Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Database" is reinitialized and closed on each call #139

Open
BranislavLazic opened this issue Dec 14, 2022 · 2 comments
Open

"Database" is reinitialized and closed on each call #139

BranislavLazic opened this issue Dec 14, 2022 · 2 comments

Comments

@BranislavLazic
Copy link

After encountering rather poor performances in my application, I found out that the bottleneck is Slick. Further investigation discovered that the default DatabaseProvider was problematic:

object DatabaseProvider {

  val live: ZLayer[Config with JdbcProfile, Throwable, DatabaseProvider] = {
    val dbProvider = for {
      cfg <- ZIO.service[Config]
      p   <- ZIO.service[JdbcProfile]
      db   = ZIO.attempt(p.backend.Database.forConfig("", cfg))
      a   <- ZIO.acquireRelease(db)(db => ZIO.succeed(db.close()))
    } yield new DatabaseProvider {
      override val db: UIO[JdbcBackend#Database] = ZIO.succeed(a)
      override val profile: UIO[JdbcProfile]     = ZIO.succeed(p)
    }

    ZLayer.scoped(dbProvider)
  }
}

The "Database" is reinitialized and closed after each call of ZIO.fromDBIO( ... ) leading to poor performances.
My temporary fix:

  private val database = Database.forConfig("", dbConfig)

  private val dbProvider = ZIO.service[JdbcProfile].map { prof =>
    new DatabaseProvider {
      override val db: UIO[JdbcBackend#Database] = ZIO.succeed(database)
      override val profile: UIO[JdbcProfile]     = ZIO.succeed(prof)
    }
  }

  val live: ZLayer[Config with JdbcProfile, Throwable, DatabaseProvider] = ZLayer.scoped(dbProvider)

In this case, the "Database" is initialized once and reused.

@baovitt
Copy link

baovitt commented Apr 14, 2023

Is this still a problem?

@BranislavLazic
Copy link
Author

BranislavLazic commented Apr 14, 2023

@baovitt Yes. Avoid using the lib as is since a DB pool is recreated on every call. You can either use it as I described or write your own wrapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants