2 giờ sáng và cú sập Database bất ngờ trên Production
Chuông điện thoại reo dồn dập lúc 2h15 sáng. Alert từ PagerDuty nổ liên tục: endpoint thanh toán trả về HTTP 500 với tỷ lệ lỗi vọt lên 98%. Khách hàng kẹt ở bước checkout, kênh CS quá tải.
Mở vội laptop, tôi SSH vào cụm server để tra log container:
docker logs -f --tail=100 backend-api
# Error: column users.phone_number does not exist
# at PostgresQuery.run (/app/node_modules/pg/lib/query.js:123:24)
Một lỗi cơ bản nhưng lọt qua staging. Frontend gọi camelCase phoneNumber, backend map sang phone_number. Trong khi đó, file SQL migration mới chỉ nằm trên PR mà chưa hề được chạy trên production database.
Code compile xanh rì. Unit test vẫn pass. Nhưng chạm vào dữ liệu thật thì crash ngay lập tức. Đây là kịch bản quen thuộc khi type của ứng dụng và schema database sống ở hai thế giới tách biệt.
Khoảng cách giữa TypeScript và Database Engine
1. Lệch pha giữa Migration SQL và Application Types
Nhiều team chọn cách viết migration bằng file raw SQL, sau đó tự gõ lại interface TypeScript ở tầng application:
// models/user.ts
interface User {
id: string;
phoneNumber: string; // Database thực tế đang đặt là phone_number, hoặc chưa kịp add cột!
}
Cách làm này phụ thuộc hoàn toàn vào trí nhớ con người. Chỉ cần dev đổi tên cột trong SQL mà quên update type, hoặc release code trước khi chạy migration, lỗi runtime sẽ kích nổ ngay lập tức.
2. Gánh nặng hiệu năng từ ORM truyền thống
Prisma hay TypeORM từng là lựa chọn mặc định của tôi. Nhưng khi chuyển sang Serverless và Edge Runtime (Next.js trên Vercel, Hono trên Cloudflare Workers), vấn đề bắt đầu lộ diện.
Query engine dạng Rust binary của Prisma nặng khoảng 40MB. Nó kéo cold-start time từ 80ms lên tận 800ms – 1.2s, đồng thời ngốn gấp đôi lượng RAM trên container Alpine.
Cân nhắc các giải pháp hiện nay
Phương án 1: Type-Casting thủ công với Raw Query (pg / postgres.js)
Viết raw query rồi ép kiểu as User. Cách này cho tốc độ thực thi nhanh nhất và bundle size cực nhẹ. Bù lại, type safety chỉ là ảo giác. Đổi tên cột trong database, compiler vẫn im lặng tuyệt đối.
Phương án 2: ORM dùng cú pháp riêng (Prisma)
An toàn về mặt type. Tuy nhiên, bạn phải học thêm DSL (Domain Specific Language) trong file schema.prisma và chạy lệnh sinh code trung gian. Engine binary đi kèm quá nặng cho các môi trường chạy theo event.
Phương án 3: Drizzle ORM – Single Source of Truth bằng TypeScript thuần
Drizzle tiếp cận theo hướng khác: coi TypeScript chính là schema definition language. Không binary engine. Không sinh file trung gian phức tạp. Type tự động suy diễn từ code và câu lệnh SQL sinh ra luôn tường minh.
Từng bước triển khai Drizzle ORM với PostgreSQL
Bước 1: Cài đặt dependencies
Dù dùng Next.js App Router hay microservice Hono, bạn chỉ cần những package sau:
npm install drizzle-orm postgres
npm install -D drizzle-kit tsx dotenv @types/pg
Bước 2: Định nghĩa Schema Type-Safe chuẩn chỉnh
Tạo file src/db/schema.ts. Toàn bộ cấu trúc bảng, kiểu dữ liệu và ràng buộc đều viết bằng TypeScript:
import { pgTable, serial, text, varchar, timestamp, boolean } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
fullName: varchar('full_name', { length: 256 }).notNull(),
email: text('email').notNull().unique(),
phoneNumber: varchar('phone_number', { length: 20 }),
isActive: boolean('is_active').default(true).notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
});
// Type inference tự động: sửa schema là type tự cập nhật theo
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
Không cần gõ tay interface riêng. Đổi tên cột ở schema, toàn bộ chỗ dùng sai type trong codebase sẽ báo đỏ ngay khi gõ phím.
Bước 3: Cấu hình Drizzle Kit để quản lý Migration
Tạo file drizzle.config.ts tại thư mục gốc:
import { defineConfig } from 'drizzle-kit';
import * as dotenv from 'dotenv';
dotenv.config();
export default defineConfig({
schema: './src/db/schema.ts',
out: './drizzle/migrations',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
strict: true,
verbose: true,
});
Khai báo thêm scripts vào package.json:
{
"scripts": {
"db:generate": "drizzle-kit generate",
"db:migrate": "tsx src/db/migrate.ts",
"db:studio": "drizzle-kit studio"
}
}
Mỗi khi chỉnh sửa schema, bạn chạy:
npm run db:generate
Drizzle Kit sẽ đối soát schema TypeScript với snapshot cũ và sinh ra file SQL tuần tự trong thư mục ./drizzle/migrations. Bạn nắm rõ 100% câu lệnh DDL nào sắp sửa thực thi trên database.
Bước 4: Viết script chạy Migration tự động khi khởi động
Để ngăn lỗi schema lệch pha, hãy chạy migration tự động trước khi app mở cổng nhận request. Tạo file src/db/migrate.ts:
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
import * as dotenv from 'dotenv';
dotenv.config();
const runMigrations = async () => {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error('DATABASE_URL is not set');
}
// Migration chỉ cần đúng 1 connection duy nhất
const sql = postgres(connectionString, { max: 1 });
const db = drizzle(sql);
console.log('⏳ Đang kiểm tra và áp dụng migrations...');
await migrate(db, { migrationsFolder: './drizzle/migrations' });
console.log('✅ Migrations hoàn tất.');
await sql.end();
process.exit(0);
};
runMigrations().catch((err) => {
console.error('❌ Migration thất bại:', err);
process.exit(1);
});
Bước 5: Tích hợp vào Hono API và Next.js
Khởi tạo singleton client trong file src/db/index.ts để tránh tràn pool kết nối lúc hot-reload:
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
const connectionString = process.env.DATABASE_URL!;
const globalForDb = globalThis as unknown as { conn: postgres.Sql | undefined };
const client = globalForDb.conn ?? postgres(connectionString);
if (process.env.NODE_ENV !== 'production') globalForDb.conn = client;
export const db = drizzle(client, { schema });
Khi dùng với Hono API, code ngắn gọn và giữ trọn type safety:
import { Hono } from 'hono';
import { db } from './db';
import { users } from './db/schema';
import { eq } from 'drizzle-orm';
const app = new Hono();
app.get('/users/:id', async (c) => {
const id = Number(c.req.param('id'));
if (Number.isNaN(id)) {
return c.json({ error: 'ID không hợp lệ' }, 400);
}
const result = await db.select().from(users).where(eq(users.id, id)).limit(1);
if (result.length === 0) {
return c.json({ error: 'Không tìm thấy user' }, 404);
}
return c.json({ data: result[0] });
});
export default app;
Với Next.js Server Action, bạn tái sử dụng trực tiếp kiểu dữ liệu đã infer:
// app/actions/create-user.ts
'use server';
import { db } from '@/db';
import { users, type NewUser } from '@/db/schema';
export async function createUser(data: NewUser) {
const [inserted] = await db.insert(users).values(data).returning();
return inserted;
}
Kinh nghiệm vận hành Production
Drizzle ORM giúp bạn giải quyết triệt để bài toán đồng bộ type giữa code và database, đồng thời giữ bundle size ở mức tối thiểu. Trong pipeline CI/CD, hãy đặt lệnh npm run db:migrate vào entrypoint của container hoặc step tiền deploy. Khi schema code và database luôn đi cùng một nhịp, hệ thống sẽ chạy ổn định và bạn có thể yên tâm ngủ ngon qua đêm.
