Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

perf: refactor clickhouseClient creation to singletons (#6584)

Steffen Schmitz7a74f7da9d9e
diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.ts
index deae69557f..1db399c51f 100644
--- a/packages/shared/src/server/clickhouse/client.ts
+++ b/packages/shared/src/server/clickhouse/client.ts
@@ -6,42 +6,112 @@ import { propagation, context } from "@opentelemetry/api";
export type ClickhouseClientType = ReturnType<typeof createClient>;
-export const clickhouseClient = (
- params: {
- tags?: Record<string, string>;
- opts?: NodeClickHouseClientConfigOptions;
- } = {},
-) => {
- const headers = params.opts?.http_headers ?? {};
- const activeSpan = getCurrentSpan();
- if (activeSpan) {
- propagation.inject(context.active(), headers);
+/**
+ * ClickHouseClientManager provides a singleton pattern for managing ClickHouse clients.
+ * It creates and reuses clients based on their configuration to avoid creating
+ * a new connection for each query.
+ */
+export class ClickHouseClientManager {
+ private static instance: ClickHouseClientManager;
+ private clientMap: Map<string, ClickhouseClientType> = new Map();
+
+ /**
+ * Private constructor to enforce singleton pattern
+ */
+ private constructor() {}
+
+ /**
+ * Get the singleton instance of the ClickHouseClientManager
+ */
+ public static getInstance(): ClickHouseClientManager {
+ if (!ClickHouseClientManager.instance) {
+ ClickHouseClientManager.instance = new ClickHouseClientManager();
+ }
+ return ClickHouseClientManager.instance;
+ }
+
+ /**
+ * Generate a consistent hash key for client configurations
+ * @param opts Client parameters
+ * @returns String hash key
+ */
+ private generateClientSettingsKey(
+ opts: NodeClickHouseClientConfigOptions,
+ ): string {
+ const keyParams = {
+ url: env.CLICKHOUSE_URL,
+ username: env.CLICKHOUSE_USER,
+ password: env.CLICKHOUSE_PASSWORD,
+ database: env.CLICKHOUSE_DB,
+ http_headers: opts?.http_headers,
+ settings: opts?.clickhouse_settings,
+ // Include any other relevant config options
+ };
+
+ return JSON.stringify(keyParams);
+ }
+
+ /**
+ * Get or create a client based on the provided parameters
+ * @param opts Client configuration parameters
+ * @returns ClickHouse client instance
+ */
+ public getClient(
+ opts: NodeClickHouseClientConfigOptions,
+ ): ClickhouseClientType {
+ const key = this.generateClientSettingsKey(opts);
+
+ if (!this.clientMap.has(key)) {
+ const headers = opts?.http_headers ?? {};
+ const activeSpan = getCurrentSpan();
+ if (activeSpan) {
+ propagation.inject(context.active(), headers);
+ }
+
+ const cloudOptions: Record<string, unknown> = {};
+ if (
+ ["STAGING", "EU", "US"].includes(
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ?? "",
+ )
+ ) {
+ cloudOptions.input_format_json_throw_on_bad_escape_sequence = 0;
+ }
+
+ const client = createClient({
+ ...opts,
+ url: env.CLICKHOUSE_URL,
+ username: env.CLICKHOUSE_USER,
+ password: env.CLICKHOUSE_PASSWORD,
+ database: env.CLICKHOUSE_DB,
+ http_headers: headers,
+ clickhouse_settings: {
+ ...cloudOptions,
+ ...opts.clickhouse_settings,
+ async_insert: 1,
+ wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse
+ },
+ });
+
+ this.clientMap.set(key, client);
+ }
+
+ return this.clientMap.get(key)!;
}
- const cloudOptions: Record<string, unknown> = {};
- if (
- ["STAGING", "EU", "US"].includes(
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ?? "",
- )
- ) {
- cloudOptions.input_format_json_throw_on_bad_escape_sequence = 0;
+ /**
+ * Close all client connections - useful for application shutdown
+ */
+ public closeAllConnections(): Promise<void[]> {
+ const closePromises = Array.from(this.clientMap.values()).map((client) =>
+ client.close(),
+ );
+ this.clientMap.clear();
+ return Promise.all(closePromises);
}
+}
- return createClient({
- ...params.opts,
- url: env.CLICKHOUSE_URL,
- username: env.CLICKHOUSE_USER,
- password: env.CLICKHOUSE_PASSWORD,
- database: env.CLICKHOUSE_DB,
- http_headers: headers,
- clickhouse_settings: {
- ...cloudOptions,
- ...(params.opts?.clickhouse_settings ?? {}),
- log_comment: JSON.stringify(params.tags ?? {}),
- async_insert: 1,
- wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse
- },
- });
+export const clickhouseClient = (opts?: NodeClickHouseClientConfigOptions) => {
+ return ClickHouseClientManager.getInstance().getClient(opts ?? {});
};
/**
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index 59a414bdb4..debfd89c47 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -57,9 +57,7 @@ export async function upsertClickhouse<
// Write new file directly to ClickHouse. We don't use the ClickHouse writer here as we expect more limited traffic
// and are not worried that much about latency.
- await clickhouseClient({
- tags: opts.tags,
- }).insert({
+ await clickhouseClient().insert({
table: "blob_storage_file_log",
values: [
{
@@ -75,6 +73,9 @@ export async function upsertClickhouse<
},
],
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: JSON.stringify(opts.tags ?? {}),
+ },
});
return getS3StorageServiceClient(
@@ -90,13 +91,16 @@ export async function upsertClickhouse<
}),
);
- const res = await clickhouseClient({ tags: opts.tags }).insert({
+ const res = await clickhouseClient().insert({
table: opts.table,
values: opts.records.map((record) => ({
...record,
event_ts: convertDateToClickhouseDateTime(new Date()),
})),
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: JSON.stringify(opts.tags ?? {}),
+ },
});
// same logic as for prisma. we want to see queries in development
if (env.NODE_ENV === "development") {
@@ -141,13 +145,13 @@ export async function* queryClickhouseStream<T>(opts: {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
- const res = await clickhouseClient({
- tags: opts.tags,
- opts: opts.clickhouseConfigs,
- }).query({
+ const res = await clickhouseClient(opts.clickhouseConfigs).query({
query: opts.query,
format: "JSONEachRow",
query_params: opts.params,
+ clickhouse_settings: {
+ log_comment: JSON.stringify(opts.tags ?? {}),
+ },
});
// same logic as for prisma. we want to see queries in development
if (env.NODE_ENV === "development") {
@@ -197,13 +201,13 @@ export async function queryClickhouse<T>(opts: {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
- const res = await clickhouseClient({
- tags: opts.tags,
- opts: opts.clickhouseConfigs,
- }).query({
+ const res = await clickhouseClient(opts.clickhouseConfigs).query({
query: opts.query,
format: "JSONEachRow",
query_params: opts.params,
+ clickhouse_settings: {
+ log_comment: JSON.stringify(opts.tags ?? {}),
+ },
});
// same logic as for prisma. we want to see queries in development
if (env.NODE_ENV === "development") {
@@ -243,12 +247,12 @@ export async function commandClickhouse(opts: {
return await instrumentAsync({ name: "clickhouse-command" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
- const res = await clickhouseClient({
- tags: opts.tags,
- opts: opts.clickhouseConfigs,
- }).command({
+ const res = await clickhouseClient(opts.clickhouseConfigs).command({
query: opts.query,
query_params: opts.params,
+ clickhouse_settings: {
+ log_comment: JSON.stringify(opts.tags ?? {}),
+ },
});
// same logic as for prisma. we want to see queries in development
if (env.NODE_ENV === "development") {
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index 401fb533e5..1639e4df1c 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -1806,10 +1806,8 @@ describe("queryBuilder", () => {
const result = await (
await clickhouseClient({
- opts: {
- clickhouse_settings: {
- date_time_output_format: "iso",
- },
+ clickhouse_settings: {
+ date_time_output_format: "iso",
},
}).query({
query: compiledQuery,
diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.ts
index 629597825c..7431021c13 100644
--- a/web/src/features/datasets/server/service.ts
+++ b/web/src/features/datasets/server/service.ts
@@ -162,13 +162,13 @@ export const insertPostgresDatasetRunsIntoClickhouse = async (
})),
);
- await clickhouseClient({
- tags: { feature: "dataset", projectId },
- opts: { session_id: clickhouseSession },
- }).insert({
+ await clickhouseClient({ session_id: clickhouseSession }).insert({
table: tableName,
values: rows,
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: JSON.stringify({ feature: "dataset", projectId }),
+ },
});
};
diff --git a/web/src/utils/shutdown.ts b/web/src/utils/shutdown.ts
index 06fbb65e2b..1c23453b22 100644
--- a/web/src/utils/shutdown.ts
+++ b/web/src/utils/shutdown.ts
@@ -4,7 +4,11 @@
// NEVER call process.exit() in this process. Kubernetes should kill the container: https://kostasbariotis.com/why-you-should-not-use-process-exit/
// We wait for 110 seconds to allow the app to finish processing requests. There is no native way to do this in Next.js.
-import { logger, redis } from "@langfuse/shared/src/server";
+import {
+ ClickHouseClientManager,
+ logger,
+ redis,
+} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
@@ -36,6 +40,9 @@ export const shutdown = async (signal: PrexitSignal) => {
setTimeout(async () => {
RateLimitService.shutdown();
+ // Shutdown clickhouse connections
+ await ClickHouseClientManager.getInstance().closeAllConnections();
+
logger.info(`Redis status ${redis?.status}`);
if (!redis) {
return;
diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.ts
index f443a8811a..f5ccfa715b 100644
--- a/worker/src/queues/ingestionQueue.ts
+++ b/worker/src/queues/ingestionQueue.ts
@@ -202,12 +202,7 @@ export const ingestionQueueProcessorBuilder = (
redis,
prisma,
clickhouseWriter,
- clickhouseClient({
- tags: {
- feature: "ingestion",
- projectId: job.data.payload.authCheck.scope.projectId,
- },
- }),
+ clickhouseClient(),
).mergeAndWrite(
getClickhouseEntityType(events[0].type),
job.data.payload.authCheck.scope.projectId,
diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.ts
index 48ace54e4e..c374680b28 100644
--- a/worker/src/services/ClickhouseWriter/index.ts
+++ b/worker/src/services/ClickhouseWriter/index.ts
@@ -212,14 +212,14 @@ export class ClickhouseWriter {
}): Promise<void> {
const startTime = Date.now();
- await (
- ClickhouseWriter.client ??
- clickhouseClient({ tags: { feature: "ingestion" } })
- )
+ await (ClickhouseWriter.client ?? clickhouseClient())
.insert({
table: params.table,
format: "JSONEachRow",
values: params.records,
+ clickhouse_settings: {
+ log_comment: JSON.stringify({ feature: "ingestion" }),
+ },
})
.catch((err) => {
logger.error(`ClickhouseWriter.writeToClickhouse ${err}`);
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 723ec59f75..ecad02c454 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -902,6 +902,12 @@ export class IngestionService {
`,
format: "JSONEachRow",
query_params: { projectId, entityId, ...additionalFilters.params },
+ clickhouse_settings: {
+ log_comment: JSON.stringify({
+ feature: "ingestion",
+ projectId,
+ }),
+ },
});
const result = await queryResult.json();
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index 403de54f78..6af86310a0 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -1,4 +1,4 @@
-import { logger } from "@langfuse/shared/src/server";
+import { ClickHouseClientManager, logger } from "@langfuse/shared/src/server";
import { redis } from "@langfuse/shared/src/server";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
@@ -23,6 +23,9 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
// Shutdown background migrations
await BackgroundMigrationManager.close();
+ // Shutdown clickhouse connections
+ await ClickHouseClientManager.getInstance().closeAllConnections();
+
// Flush all pending writes to Clickhouse AFTER closing ingestion queue worker that is writing to it
await ClickhouseWriter.getInstance().shutdown();
logger.info("Clickhouse writer has been shut down.");