Skip to content

Commit 1d2f53c

Browse files
committed
Fix Worker hang: use per-request connections instead of cached pool
The module-level cached mysql2 pool could hold stale connections when the Worker isolate went idle, causing the next request to hang forever. Switch from createPool (cached) to createConnection (per-request) with proper cleanup via connection.end() in a finally block. Hyperdrive handles actual connection pooling at the edge, so mysql2 pooling is unnecessary and harmful. Also adds connectTimeout: 5000 as a safety net. https://claude.ai/code/session_01K4SCzhd53zgSyEEoNPF59B
1 parent cdda6ee commit 1d2f53c

1 file changed

Lines changed: 17 additions & 23 deletions

File tree

src/db/index.ts

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,25 @@
11
import { getCloudflareContext } from "@opennextjs/cloudflare";
22
import { drizzle, type MySql2Database } from "drizzle-orm/mysql2";
3-
import { createPool } from "mysql2/promise";
3+
import { createConnection } from "mysql2/promise";
44
import * as schema from "./schema";
55

66
export type Db = MySql2Database<typeof schema>;
77

8-
let _db: Db | undefined;
9-
10-
export function getDb(): Db {
11-
if (_db) return _db;
12-
13-
const { env } = getCloudflareContext();
14-
_db = drizzle(
15-
createPool({
16-
host: env.HYPERDRIVE.host,
17-
user: env.HYPERDRIVE.user,
18-
password: env.HYPERDRIVE.password,
19-
database: env.HYPERDRIVE.database,
20-
port: env.HYPERDRIVE.port,
21-
disableEval: true,
22-
connectionLimit: 1,
23-
}),
24-
{ schema, mode: "default" },
25-
);
26-
return _db;
27-
}
28-
298
export async function withDb<T>(callback: (db: Db) => Promise<T>): Promise<T> {
30-
return callback(getDb());
9+
const { env } = getCloudflareContext();
10+
const connection = await createConnection({
11+
host: env.HYPERDRIVE.host,
12+
user: env.HYPERDRIVE.user,
13+
password: env.HYPERDRIVE.password,
14+
database: env.HYPERDRIVE.database,
15+
port: env.HYPERDRIVE.port,
16+
disableEval: true,
17+
connectTimeout: 5000,
18+
});
19+
const db = drizzle(connection, { schema, mode: "default" });
20+
try {
21+
return await callback(db);
22+
} finally {
23+
await connection.end();
24+
}
3125
}

0 commit comments

Comments
 (0)