Read Replicas

프로젝트에서 읽기 전용 복제본(read replica) 인스턴스 세트를 사용하고, 읽기 전용 복제본에서 SELECT 쿼리를 관리하고 기본 인스턴스에서 생성, 삭제, 업데이트 작업을 수행하는 편리한 방법이 필요한 경우, Drizzle의 withReplicas() 함수를 활용할 수 있습니다

PostgreSQL
MySQL
SQLite
SingleStore
MSSQL
CockroachDB
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { boolean, jsonb, pgTable, serial, text, timestamp, withReplicas } from 'drizzle-orm/pg-core';

const usersTable = pgTable('users', {
	id: serial('id' as string).primaryKey(),
	name: text('name').notNull(),
	verified: boolean('verified').notNull().default(false),
	jsonb: jsonb('jsonb').$type<string[]>(),
	createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});

const primaryDb = drizzle("postgres://user:password@host:port/primary_db");
const read1 = drizzle("postgres://user:password@host:port/read_replica_1");
const read2 = drizzle("postgres://user:password@host:port/read_replica_2");

const db = withReplicas(primaryDb, [read1, read2]);

이제 이전과 동일한 방식으로 db 인스턴스를 사용할 수 있습니다. Drizzle은 읽기 전용 복제본과 기본 인스턴스 중 자동으로 선택을 처리합니다

// read1 연결 또는 read2 연결에서 읽기
await db.select().from(usersTable)

// 삭제 작업에는 기본 데이터베이스 사용
await db.delete(usersTable).where(eq(usersTable.id, 1))

읽기 작업에서도 기본 인스턴스를 강제로 사용하려면 $primary 키를 사용할 수 있습니다

// 기본 인스턴스에서 읽기
await db.$primary.select().from(usersTable);

Drizzle을 사용하면 읽기 전용 복제본 선택을 위한 사용자 정의 로직을 지정할 수도 있습니다. 가중치 기반 결정이나 임의의 읽기 전용 복제본 선택을 위한 기타 사용자 정의 선택 방법을 만들 수 있습니다. 다음은 읽기 전용 복제본 선택을 위한 사용자 정의 로직의 구현 예시로, 첫 번째 복제본은 70%의 확률로 선택되고 두 번째 복제본은 30%의 확률로 선택됩니다.

읽기 전용 복제본에 대한 모든 유형의 임의 선택 방법을 구현할 수 있습니다

const db = withReplicas(primaryDb, [read1, read2], (replicas) => {
    const weight = [0.7, 0.3];
    let cumulativeProbability = 0;
    const rand = Math.random();

    for (const [i, replica] of replicas.entries()) {
      cumulativeProbability += weight[i]!;
      if (rand < cumulativeProbability) return replica;
    }
    return replicas[0]!
});

await db.select().from(usersTable)