Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(api): make the database pool size configurable (#2042)

Alexander Wolffcfe528c1a724
diff --git a/.env.sample b/.env.sample
index 2a2b23568..dcfd1ffd7 100644
--- a/.env.sample
+++ b/.env.sample
@@ -12,6 +12,7 @@ POSTGRES_PASSWORD=
# Alternatively, mount a secret file and set POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password
# POSTGRES_HOST=postgres # Compose container default; use localhost for host-native API startup
# POSTGRES_PORT=5432
+# DATABASE_POOL_MAX=10 # max connections per API process (min 2); lower it if the DB user has a connection limit
# Note: POSTGRES_DB and POSTGRES_USER alone do not enable derived connection mode.
# Derived DATABASE_URL is only used when POSTGRES_PASSWORD or an explicit host/port is set.
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.ts
index 09f91bc04..e3a477fab 100644
--- a/apps/api/src/database/index.ts
+++ b/apps/api/src/database/index.ts
@@ -34,7 +34,7 @@ import {
workspaceTableRelations,
workspaceUserTableRelations,
} from "./relations";
-import { resolveDatabaseConnectionString } from "./resolve-database-url";
+import { resolveDatabaseConfig } from "./resolve-database-url";
import {
dataMigrationTable,
storageCleanupTable,
@@ -173,13 +173,14 @@ let dbInstance: DatabaseInstance | undefined;
export function getDatabasePool(): Pool {
if (!pool) {
+ const config = resolveDatabaseConfig();
pool = new Pool({
- connectionString: resolveDatabaseConnectionString(),
+ connectionString: config.connectionString,
// Fail fast when Railway's internal network is slow rather than hanging
// indefinitely and blocking every API request.
connectionTimeoutMillis: 5_000,
idleTimeoutMillis: 30_000,
- max: 10,
+ max: config.poolMax,
});
}
diff --git a/apps/api/src/database/pool-config.ts b/apps/api/src/database/pool-config.ts
new file mode 100644
index 000000000..3e48f97dc
--- /dev/null
+++ b/apps/api/src/database/pool-config.ts
@@ -0,0 +1,24 @@
+const DEFAULT_POOL_MAX = 10;
+// Session-lock holders pin one client while their work queries through the
+// pool, so a single client could never serve both.
+const MIN_POOL_MAX = 2;
+
+export function resolveDatabasePoolMax(): number {
+ const raw = process.env.DATABASE_POOL_MAX?.trim();
+ if (!raw) {
+ return DEFAULT_POOL_MAX;
+ }
+
+ const value = Number(raw);
+ if (
+ !/^[1-9]\d*$/.test(raw) ||
+ !Number.isSafeInteger(value) ||
+ value < MIN_POOL_MAX
+ ) {
+ throw new Error(
+ `DATABASE_POOL_MAX must be an integer of at least ${MIN_POOL_MAX}`,
+ );
+ }
+
+ return value;
+}
diff --git a/apps/api/src/database/resolve-database-url.ts b/apps/api/src/database/resolve-database-url.ts
index 315439964..7d4b3c2b6 100644
--- a/apps/api/src/database/resolve-database-url.ts
+++ b/apps/api/src/database/resolve-database-url.ts
@@ -1,4 +1,5 @@
import { resolveFileSecret } from "../utils/file-secret";
+import { resolveDatabasePoolMax } from "./pool-config";
const LOCAL_FALLBACK_CONNECTION_STRING = "postgresql://localhost:5432/kaneo";
@@ -11,12 +12,14 @@ export type ResolvedDatabaseConfig = {
port: number;
database: string;
username: string;
+ poolMax: number;
logConfig: {
source: DatabaseConfigSource;
host: string;
port: number;
database: string;
username: string;
+ poolMax: number;
};
};
@@ -41,6 +44,7 @@ function toResolvedConfig(
port: Number(url.port || 5432),
database: url.pathname.replace(/^\//, ""),
username: decodeURIComponent(url.username),
+ poolMax: resolveDatabasePoolMax(),
};
return {
diff --git a/apps/api/src/database/session-lock-budget.ts b/apps/api/src/database/session-lock-budget.ts
new file mode 100644
index 000000000..a4721f263
--- /dev/null
+++ b/apps/api/src/database/session-lock-budget.ts
@@ -0,0 +1,14 @@
+import { getDatabasePool } from ".";
+
+let held = 0;
+
+/** Holders pin a pooled client, so one always stays free for their queries. */
+export function reserveSessionLock(): boolean {
+ if (held >= getDatabasePool().options.max - 1) return false;
+ held++;
+ return true;
+}
+
+export function releaseSessionLock() {
+ held--;
+}
diff --git a/apps/api/src/github-integration/import-lock.ts b/apps/api/src/github-integration/import-lock.ts
index b4442d610..d2b2c222d 100644
--- a/apps/api/src/github-integration/import-lock.ts
+++ b/apps/api/src/github-integration/import-lock.ts
@@ -1,6 +1,10 @@
import { HTTPException } from "hono/http-exception";
import type { PoolClient } from "pg";
import { getDatabasePool } from "../database";
+import {
+ releaseSessionLock,
+ reserveSessionLock,
+} from "../database/session-lock-budget";
export const MAX_GITHUB_IMPORTS_IN_FLIGHT = 2;
const LOCK_NAMESPACE = 773623;
@@ -20,7 +24,8 @@ export async function withGithubImportLock<T>(
id: string,
run: () => Promise<T>,
): Promise<T> {
- if (active >= MAX_GITHUB_IMPORTS_IN_FLIGHT) throw busy();
+ if (active >= MAX_GITHUB_IMPORTS_IN_FLIGHT || !reserveSessionLock())
+ throw busy();
active++;
let client: PoolClient | undefined;
let slot: number | undefined;
@@ -72,6 +77,7 @@ export async function withGithubImportLock<T>(
}
client.release(releaseError);
}
+ releaseSessionLock();
active--;
}
}
diff --git a/apps/api/src/label/deletion-lock.ts b/apps/api/src/label/deletion-lock.ts
index 48634e7b6..884b89edf 100644
--- a/apps/api/src/label/deletion-lock.ts
+++ b/apps/api/src/label/deletion-lock.ts
@@ -1,6 +1,10 @@
import { HTTPException } from "hono/http-exception";
import type { PoolClient } from "pg";
import { getDatabasePool } from "../database";
+import {
+ releaseSessionLock,
+ reserveSessionLock,
+} from "../database/session-lock-budget";
export const MAX_LABEL_DELETIONS_IN_FLIGHT = 4;
const LOCK_NAMESPACE = 773622;
@@ -20,7 +24,8 @@ export async function withLabelDeletionLock<T>(
id: string,
run: () => Promise<T>,
): Promise<T> {
- if (active >= MAX_LABEL_DELETIONS_IN_FLIGHT) throw busy();
+ if (active >= MAX_LABEL_DELETIONS_IN_FLIGHT || !reserveSessionLock())
+ throw busy();
active++;
let client: PoolClient | undefined;
let slot: number | undefined;
@@ -72,6 +77,7 @@ export async function withLabelDeletionLock<T>(
}
client.release(releaseError);
}
+ releaseSessionLock();
active--;
}
}
diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdx
index b847a6c01..0365f87a3 100644
--- a/apps/docs/core/installation/environment-variables.mdx
+++ b/apps/docs/core/installation/environment-variables.mdx
@@ -41,6 +41,7 @@ Name | Description |
| `POSTGRES_HOST` | Database hostname for derived configuration. Default: `postgres`; use `localhost` for a host-native API connected to local PostgreSQL. |
| `POSTGRES_PORT` | Database port for derived configuration. Default: `5432`. |
| `POSTGRES_PASSWORD_FILE` | Path to a UTF-8 file containing the database password. Used when `POSTGRES_PASSWORD` is unset and Kaneo derives `DATABASE_URL` from `POSTGRES_*`. Set the same file variable on the PostgreSQL container when using the bundled Compose setup; see [Keep secrets in files](/core/installation/docker-compose#keep-secrets-in-files). |
+| `DATABASE_POOL_MAX` | Maximum number of PostgreSQL connections each API process keeps open. Default: `10`. Lower it when the database user has a connection limit, for example on a shared PostgreSQL server; with several API replicas, the limit has to cover all of them. Label deletions and GitHub imports running at once beyond the pool size minus one get a retryable `429`. Must be an integer of at least `2`, otherwise startup fails. |
### Authentication
diff --git a/tests/api-integration/session-lock-budget.test.ts b/tests/api-integration/session-lock-budget.test.ts
new file mode 100644
index 000000000..553c8afca
--- /dev/null
+++ b/tests/api-integration/session-lock-budget.test.ts
@@ -0,0 +1,90 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import db, { getDatabasePool, schema } from "../../apps/api/src/database";
+import { withGithubImportLock } from "../../apps/api/src/github-integration/import-lock";
+import { createApp } from "../../apps/api/src/index";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+const github = vi.hoisted(() =>
+ vi.fn(async (_id: string, _name: string) => {}),
+);
+vi.mock("../../apps/api/src/plugins/github/utils/sync-label-to-github", () => ({
+ removeLabelFromGitHub: github,
+ syncLabelToGitHub: vi.fn(),
+}));
+// Set this before the lazy database pool opens any connections.
+vi.stubEnv("DATABASE_POOL_MAX", "2");
+afterAll(() => vi.unstubAllEnvs());
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+beforeEach(async () => {
+ await resetTestDatabase();
+ github.mockReset().mockResolvedValue();
+});
+
+describe("session locks with DATABASE_POOL_MAX=2", () => {
+ it("returns 429 to a lock holder beyond pool size - 1 instead of timing out its queries", async () => {
+ expect(getDatabasePool().options.max).toBe(2);
+ const member = await createWorkspaceMember({ role: "admin" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Task",
+ status: "to-do",
+ number: 1,
+ })
+ .returning();
+ const [first, second] = await db
+ .insert(schema.labelTable)
+ .values(
+ ["bug", "docs"].map((name) => ({
+ workspaceId: member.workspace.id,
+ taskId: task.id,
+ name,
+ color: "red",
+ })),
+ )
+ .returning();
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const remove = (id: string) =>
+ app.request(`/api/label/${id}`, { method: "DELETE" });
+
+ const gate = deferred();
+ github.mockImplementationOnce(() => gate.promise);
+ const admitted = remove(first.id);
+ try {
+ await vi.waitFor(() => expect(github).toHaveBeenCalledTimes(1));
+ const busy = await remove(second.id);
+ expect(busy.status).toBe(429);
+ expect(busy.headers.get("Retry-After")).toBe("1");
+ await expect(
+ withGithubImportLock(project.id, async () => "must not run"),
+ ).rejects.toMatchObject({ status: 429 });
+ } finally {
+ gate.resolve();
+ }
+ expect((await admitted).status).toBe(200);
+
+ expect((await remove(second.id)).status).toBe(200);
+ expect(
+ await withGithubImportLock(project.id, () =>
+ db.query.labelTable.findMany(),
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/tests/api/database/pool-config.test.ts b/tests/api/database/pool-config.test.ts
new file mode 100644
index 000000000..90e8dfa34
--- /dev/null
+++ b/tests/api/database/pool-config.test.ts
@@ -0,0 +1,41 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { resolveDatabasePoolMax } from "../../../apps/api/src/database/pool-config";
+
+describe("pool-config", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("defaults the pool size to 10 when DATABASE_POOL_MAX is unset or empty", () => {
+ vi.stubEnv("DATABASE_POOL_MAX", undefined);
+ expect(resolveDatabasePoolMax()).toBe(10);
+
+ vi.stubEnv("DATABASE_POOL_MAX", " ");
+ expect(resolveDatabasePoolMax()).toBe(10);
+ });
+
+ it("uses DATABASE_POOL_MAX as the pool size", () => {
+ vi.stubEnv("DATABASE_POOL_MAX", "2");
+ expect(resolveDatabasePoolMax()).toBe(2);
+
+ vi.stubEnv("DATABASE_POOL_MAX", " 25 ");
+ expect(resolveDatabasePoolMax()).toBe(25);
+ });
+
+ it("rejects a DATABASE_POOL_MAX that is not an integer of at least 2", () => {
+ for (const value of [
+ "1",
+ "0",
+ "-1",
+ "2.5",
+ "1e1",
+ "ten",
+ "05",
+ "9007199254740993",
+ "9".repeat(309),
+ ]) {
+ vi.stubEnv("DATABASE_POOL_MAX", value);
+ expect(() => resolveDatabasePoolMax()).toThrow(
+ "DATABASE_POOL_MAX must be an integer of at least 2",
+ );
+ }
+ });
+});
diff --git a/tests/api/database/prepare-database-startup.test.ts b/tests/api/database/prepare-database-startup.test.ts
index 981d7d5af..9bedb146f 100644
--- a/tests/api/database/prepare-database-startup.test.ts
+++ b/tests/api/database/prepare-database-startup.test.ts
@@ -13,12 +13,14 @@ describe("prepare-database-startup", () => {
port: 5432,
database: "kaneo",
username: "kaneo",
+ poolMax: 10,
logConfig: {
source: "POSTGRES_ENV",
host: "postgres",
port: 5432,
database: "kaneo",
username: "kaneo",
+ poolMax: 10,
},
}),
waitForDatabase: async () => {
@@ -49,12 +51,14 @@ describe("prepare-database-startup", () => {
port: 5432,
database: "kaneo",
username: "kaneo",
+ poolMax: 10,
logConfig: {
source: "POSTGRES_ENV",
host: "postgres",
port: 5432,
database: "kaneo",
username: "kaneo",
+ poolMax: 10,
},
}),
waitForDatabase: async () => {
@@ -94,12 +98,14 @@ describe("prepare-database-startup", () => {
port: 5432,
database: "kaneo",
username: "kaneo",
+ poolMax: 10,
logConfig: {
source: "POSTGRES_ENV",
host: "postgres",
port: 5432,
database: "kaneo",
username: "kaneo",
+ poolMax: 10,
},
}),
waitForDatabase: async () => undefined,
@@ -147,4 +153,35 @@ describe("prepare-database-startup", () => {
configError,
);
});
+
+ it("rejects an invalid DATABASE_POOL_MAX before waiting for the database", async () => {
+ const original = {
+ DATABASE_URL: process.env.DATABASE_URL,
+ DATABASE_POOL_MAX: process.env.DATABASE_POOL_MAX,
+ };
+ process.env.DATABASE_URL =
+ "postgresql://kaneo:password@postgres:5432/kaneo";
+ process.env.DATABASE_POOL_MAX = "not-a-number";
+ const waitForDatabase = vi.fn(async () => undefined);
+
+ try {
+ await expect(
+ prepareDatabaseStartup({
+ waitForDatabase,
+ runStartupMigrations: async () => undefined,
+ logError: () => undefined,
+ }),
+ ).rejects.toThrow("Database configuration failed during startup.");
+
+ expect(waitForDatabase).not.toHaveBeenCalled();
+ } finally {
+ for (const [key, value] of Object.entries(original)) {
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ }
+ });
});
diff --git a/tests/api/database/resolve-database-url.test.ts b/tests/api/database/resolve-database-url.test.ts
index 4e342ef90..9e96e71a4 100644
--- a/tests/api/database/resolve-database-url.test.ts
+++ b/tests/api/database/resolve-database-url.test.ts
@@ -9,6 +9,7 @@ import {
const keys = [
"DATABASE_URL",
+ "DATABASE_POOL_MAX",
"POSTGRES_HOST",
"POSTGRES_PORT",
"POSTGRES_DB",
@@ -157,4 +158,23 @@ describe("resolve-database-url", () => {
expect(config.logConfig).not.toHaveProperty("password");
expect(JSON.stringify(config.logConfig)).not.toContain("super-secret");
});
+
+ it("includes the pool size in the resolved config and its log metadata", () => {
+ process.env.DATABASE_URL = "postgresql://app:[email protected]:5433/appdb";
+ process.env.DATABASE_POOL_MAX = "2";
+
+ const config = resolveDatabaseConfig();
+
+ expect(config.poolMax).toBe(2);
+ expect(config.logConfig.poolMax).toBe(2);
+ });
+
+ it("fails config resolution when DATABASE_POOL_MAX is invalid", () => {
+ process.env.DATABASE_URL = "postgresql://app:[email protected]:5433/appdb";
+ process.env.DATABASE_POOL_MAX = "1";
+
+ expect(() => resolveDatabaseConfig()).toThrow(
+ "DATABASE_POOL_MAX must be an integer of at least 2",
+ );
+ });
});
diff --git a/tests/api/database/session-lock-budget.test.ts b/tests/api/database/session-lock-budget.test.ts
new file mode 100644
index 000000000..07247235b
--- /dev/null
+++ b/tests/api/database/session-lock-budget.test.ts
@@ -0,0 +1,128 @@
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import {
+ releaseSessionLock,
+ reserveSessionLock,
+} from "../../../apps/api/src/database/session-lock-budget";
+import {
+ MAX_GITHUB_IMPORTS_IN_FLIGHT,
+ withGithubImportLock,
+} from "../../../apps/api/src/github-integration/import-lock";
+import {
+ MAX_LABEL_DELETIONS_IN_FLIGHT,
+ withLabelDeletionLock,
+} from "../../../apps/api/src/label/deletion-lock";
+
+const pool = vi.hoisted(() => ({ options: { max: 10 }, connect: vi.fn() }));
+vi.mock("../../../apps/api/src/database", () => ({
+ getDatabasePool: () => pool,
+}));
+
+function client({ acquired = true, unlock = true } = {}) {
+ return {
+ query: vi.fn(async (text: string) => {
+ if (!unlock && text.includes("unlock")) throw new Error("unlock failed");
+ return { rows: [{ acquired }] };
+ }),
+ release: vi.fn(),
+ };
+}
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+const helpers = [
+ ["label deletion", withLabelDeletionLock],
+ ["GitHub import", withGithubImportLock],
+] as const;
+
+beforeEach(() => {
+ pool.options.max = 10;
+ pool.connect.mockReset().mockImplementation(async () => client());
+});
+
+describe("session lock budget", () => {
+ it("leaves one pooled client free", () => {
+ for (const max of [2, 10]) {
+ pool.options.max = max;
+ let held = 0;
+ while (reserveSessionLock()) held++;
+ expect(held).toBe(max - 1);
+ for (; held > 0; held--) releaseSessionLock();
+ }
+ });
+
+ it("admits both helpers' full caps with the default pool", async () => {
+ const gate = deferred();
+ const running = [
+ ...Array.from({ length: MAX_LABEL_DELETIONS_IN_FLIGHT }, (_, i) =>
+ withLabelDeletionLock(`label-${i}`, () => gate.promise),
+ ),
+ ...Array.from({ length: MAX_GITHUB_IMPORTS_IN_FLIGHT }, (_, i) =>
+ withGithubImportLock(`import-${i}`, () => gate.promise),
+ ),
+ ];
+ for (const [, withLock] of helpers)
+ await expect(withLock("extra", async () => {})).rejects.toMatchObject({
+ status: 429,
+ });
+ gate.resolve();
+ await Promise.all(running);
+ expect(pool.connect).toHaveBeenCalledTimes(running.length);
+ });
+
+ it("shares one budget between both helpers", async () => {
+ pool.options.max = 3;
+ const gate = deferred();
+ const running = [
+ withLabelDeletionLock("label", () => gate.promise),
+ withGithubImportLock("import", () => gate.promise),
+ ];
+ for (const [, withLock] of helpers)
+ await expect(withLock("extra", async () => {})).rejects.toMatchObject({
+ status: 429,
+ });
+ expect(pool.connect).toHaveBeenCalledTimes(2);
+ gate.resolve();
+ await Promise.all(running);
+ for (const [, withLock] of helpers)
+ await expect(withLock("later", async () => "ok")).resolves.toBe("ok");
+ });
+
+ it.each(helpers)(
+ "releases the %s reservation on every path",
+ async (_, withLock) => {
+ pool.options.max = 2;
+ const budgetRestored = () => {
+ expect(reserveSessionLock()).toBe(true);
+ expect(reserveSessionLock()).toBe(false);
+ releaseSessionLock();
+ };
+
+ pool.connect.mockRejectedValueOnce(new Error("connect failed"));
+ await expect(withLock("id", async () => {})).rejects.toThrow(
+ "connect failed",
+ );
+ budgetRestored();
+
+ pool.connect.mockResolvedValueOnce(client({ acquired: false }));
+ await expect(withLock("id", async () => {})).rejects.toMatchObject({
+ status: 429,
+ });
+ budgetRestored();
+
+ await expect(
+ withLock("id", async () => {
+ throw new Error("failed");
+ }),
+ ).rejects.toThrow("failed");
+ budgetRestored();
+
+ pool.connect.mockResolvedValueOnce(client({ unlock: false }));
+ await expect(withLock("id", async () => "done")).resolves.toBe("done");
+ budgetRestored();
+ },
+ );
+});