feat: add read-replica routing and query load-balancing - #120
Conversation
Miracle656
left a comment
There was a problem hiding this comment.
Solid implementation of read-replica routing (#118). withReadReplicas uses a Prisma $extends query interceptor to send reads to round-robined healthy replicas while writes and anything inside a transaction go to the primary; the background health-check loop marks replicas unhealthy and fails over to primary, and interval.unref() keeps the process exitable. It's wired in cleanly via DATABASE_REPLICAS with a zero-config passthrough default (no replicas → primary unchanged), and the tests cover read/write routing, transaction bypass, round-robin, and unhealthy fallback. Merging — nice work!
|
@mallison031 Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
Closes #123
Adds a routing layer to
src/db.tsthat automatically routes read-heavytraffic to replicas while sending all writes to the primary database,
improving throughput and isolating ingest contention.
Extension.
- Reads (
findMany,findUnique,count, etc.) and raw queries(
$queryRaw) are now round-robined acrossDATABASE_REPLICAS.- Updated
src/db.tsto wrap the exportedprismasingleton in therouter.
- Added comprehensive unit tests for the router in
src/db/__tests__/router.test.ts.check if a query is executing inside a
$transaction. Interactivetransactions bypass replicas and route strictly to the primary, cleanly
preserving read-your-writes guarantees for all grouped operations in the
repo.
- Health Checks & Failover: A background loop continuously pings
replicas via
SELECT 1. If a replica fails a ping—or if a query fails mid-flight—it's marked unhealthy, temporarily removed from the round-robin, and
traffic gracefully falls back to the primary.
queries to primary)
(
DATABASE_REPLICAS). Connection logic avoids exposing URI components orlogging credentials.
Closes #118