prisma / extension-read-replicas

Prisma Client Extension to add read replica support to your Prisma Client
Apache License 2.0
96 stars 6 forks source link

Allow to customize replica selection function #28

Open SevInf opened 8 months ago

SevInf commented 8 months ago

By default, we select replicas randomly. Users might want to use different selection criterea: for example, round robin or weighted random selection. We should have an option to provide custom selection function.

API sketch:


let nextReplicaIndex = 0;
const prisma = new PrismaClient().$extends(
  readReplicas({
    url: [
      'postgresql://replica-1.example.com:5432/db',
      'postgresql://replica-2.example.com:5432/db',
    ],
    selectReplica(replicas) {
       // `replicas` is an array of pre-configured
       // callback is expected to return one of them
       // if `selectReplicas` is provided, it will be used by automatic selection via extension as well as explicit `$replica()` method.

       // Example of simple round robin implementation
       const replica = replicas[nextReplicaIndex]
       nextReplicaIndex = (nextReplicaIndex + 1) % replicas.length
       return replica
    }
  }),
)
divmgl commented 3 months ago

It'd also be nice if we could always issue queries against the primary and selectively choose which queries go to the replica.

bvkimball commented 1 month ago

Curious if any of these features are being implemented or if you are accepting PRs. I think this is a critical feature for people using replicas in alternative regions. I personally we want this to be filtered or chosen by lowest latency to DB or by ENV variable (for the same reason).

janpio commented 1 month ago

We are definitely accepting PRs @bvkimball. Optimally share the planned API before writing the code, so we are all on the same page.