Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
perf(api): overlap requests-row insert with v2 search work, expose DB pool gauges
mogeryc90a794514df
diff --git a/apps/api/src/controllers/v0/admin/metrics.ts b/apps/api/src/controllers/v0/admin/metrics.tsindex 6b86de3f6..9779b5475 100644--- a/apps/api/src/controllers/v0/admin/metrics.ts+++ b/apps/api/src/controllers/v0/admin/metrics.ts@@ -1,5 +1,6 @@import type { Request, Response } from "express";import { getRedisConnection } from "../../../services/queue-service";+import { getDbPoolMetrics } from "../../../db/connection";import { nuqFdbGetMetrics } from "../../../services/worker/nuq-fdb";import { nuqGetLocalMetrics } from "../../../services/worker/nuq";import { scrapeQueue } from "../../../services/worker/nuq-router";@@ -42,7 +43,8 @@ concurrency_limit_queue_job_count_total ${totalJobCount}concurrency_limit_queue_team_count ${teamCount}${nuqGetLocalMetrics()}-${semaphoreMetrics}`);+${semaphoreMetrics}+${getDbPoolMetrics()}`);}export async function nuqMetricsController(_: Request, res: Response) {diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.tsindex 543566c7f..e8892943f 100644--- a/apps/api/src/controllers/v2/search.ts+++ b/apps/api/src/controllers/v2/search.ts@@ -182,8 +182,13 @@ export async function searchController(}}+ // Kick off the `requests` row insert without blocking: it queues on the+ // Postgres pool and can take seconds under pool pressure. We only need it+ // committed before the child-row writes (logSearch et al. below) to keep+ // the request_id FK ordering — same pattern as the scrape controllers.+ let logRequestPromise: Promise<void> | undefined;if (!agentRequestId) {- await logRequest({+ logRequestPromise = logRequest({id: jobId,kind: "search",api_version: "v2",@@ -292,6 +297,12 @@ export async function searchController(const endTime = new Date().getTime();const timeTakenInSeconds = (endTime - middlewareStartTime) / 1000;+ // Ensure the parent `requests` row is committed before the child+ // `searches` insert, to avoid a request_id FK violation. The insert has+ // been in flight since the top of the controller, so this is ~free in+ // practice; robustInsert never rejects, so this await cannot throw.+ await logRequestPromise;+logSearch({id: jobId,diff --git a/apps/api/src/db/connection.test.ts b/apps/api/src/db/connection.test.tsnew file mode 100644index 000000000..3dc9bfe07--- /dev/null+++ b/apps/api/src/db/connection.test.ts@@ -0,0 +1,21 @@+import { getDbPoolMetrics } from "./connection";++describe("getDbPoolMetrics", () => {+ it("emits the four pool gauge families in Prometheus text format", () => {+ const out = getDbPoolMetrics();+ for (const metric of [+ "db_pool_waiting_count",+ "db_pool_idle_count",+ "db_pool_total_count",+ "db_pool_max_count",+ ]) {+ expect(out).toContain(`# HELP ${metric} `);+ expect(out).toContain(`# TYPE ${metric} gauge`);+ }+ // Every sample line must carry the application_name label and a number.+ const samples = out.split("\n").filter(l => l.startsWith("db_pool_"));+ for (const s of samples) {+ expect(s).toMatch(/^db_pool_\w+\{application_name="[^"]+"\} \d+$/);+ }+ });+});diff --git a/apps/api/src/db/connection.ts b/apps/api/src/db/connection.tsindex dbbb6fe12..64438803f 100644--- a/apps/api/src/db/connection.ts+++ b/apps/api/src/db/connection.ts@@ -12,6 +12,9 @@ interface PoolSizing {min?: number;}+// Registry of every pool we create, for /metrics exposure.+const dbPools: { name: string; pool: Pool }[] = [];+function makeDb(connectionString: string | undefined,applicationName: string,@@ -34,6 +37,7 @@ function makeDb(min: sizing.min ?? 0,keepAlive: true,});+ dbPools.push({ name: applicationName, pool });pool.on("error", err =>logger.error("Error in idle Postgres client", {err,@@ -65,6 +69,47 @@ function makeDb(return drizzle({ client: pool });}+/** Prometheus text-format gauges for every DB pool in this process. */+export function getDbPoolMetrics(): string {+ const lines: string[] = [+ "# HELP db_pool_waiting_count Number of queries queued waiting for a free connection in this pool",+ "# TYPE db_pool_waiting_count gauge",+ ];+ for (const { name, pool } of dbPools) {+ lines.push(+ `db_pool_waiting_count{application_name="${name}"} ${pool.waitingCount}`,+ );+ }+ lines.push(+ "# HELP db_pool_idle_count Number of idle connections in this pool",+ "# TYPE db_pool_idle_count gauge",+ );+ for (const { name, pool } of dbPools) {+ lines.push(+ `db_pool_idle_count{application_name="${name}"} ${pool.idleCount}`,+ );+ }+ lines.push(+ "# HELP db_pool_total_count Number of connections currently open in this pool",+ "# TYPE db_pool_total_count gauge",+ );+ for (const { name, pool } of dbPools) {+ lines.push(+ `db_pool_total_count{application_name="${name}"} ${pool.totalCount}`,+ );+ }+ lines.push(+ "# HELP db_pool_max_count Configured maximum connections for this pool",+ "# TYPE db_pool_max_count gauge",+ );+ for (const { name, pool } of dbPools) {+ lines.push(+ `db_pool_max_count{application_name="${name}"} ${pool.options.max ?? 20}`,+ );+ }+ return lines.join("\n");+}+const useDbAuthentication = config.USE_DB_AUTHENTICATION;const mainDb = useDbAuthentication