K
Kysely•4mo ago
bombillazo

Kysely setup in monolith API

Hello, we have a basic http server with a basic router and a PostgreSQL database. We're wondering what is the proper setup to use the Kysely client in our routes to make calls to the database. Should there be a singleton client that is used across routes, or do we need to instantiate a kysely client on every request ?
8 Replies
tzezar
tzezar•4mo ago
I don't know if I understand correctly, but I am creating one instance of
export const db = new Kysely<DB>({
dialect,
})
export const db = new Kysely<DB>({
dialect,
})
and import it where I need to make a call. There is connection pool that node-poostgres handles automatically.
bombillazo
bombillazo•4mo ago
Ok got it, no issues with max connections?
tzezar
tzezar•4mo ago
Well we have used it in several projects and in our case there were no problems. Btw if you are tempted by postgresjs with its "speed" do some tests, because I checked the performance and in theory the slower pg was about 10% faster + the average time of access to the database was lower and here you got more technical info about pools
tzezar
tzezar•4mo ago
But with kysely it basically wraps up in:
const dialect = new PostgresDialect({
pool: new Pool({
connectionString: "",
max: 10
})
})
const dialect = new PostgresDialect({
pool: new Pool({
connectionString: "",
max: 10
})
})
Johan Grundberg
Johan Grundberg•4mo ago
A bit late here but according to the docs the singleton approach seems 100% correct assuming you have a single database. From the docs: "You should create one instance of Kysely per database using the Kysely constructor. Each Kysely instance maintains it's own connection pool.".
bombillazo
bombillazo•4mo ago
Thanks for the confirmation
Igal
Igal•4mo ago
I don't like that sentence. There are nuances. You could pass the same postgres/mysql pool instance to different Kysely instances and everything would be fine if you have a new Kysely instance per request. We do some caching of kysely connection instances under the hood that might make it worth "singleton'ing" (memory / time wise), dunno. In mssql we do manage a pool per Kysely instance (we had to 😦 ), so you better singleton.
Want results from more Discord servers?
Add your server
More Posts