Skip to content

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

perf: extend model cache duration and invalidate on model changes (#8053)

Steffen Schmitz83b64f5e77af
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index a2a8e9ddc3..e493ecee78 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -32,8 +32,10 @@ const EnvSchema = z.object({
"ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32",
)
.optional(),
+ LANGFUSE_CACHE_MODEL_MATCH_ENABLED: z.enum(["true", "false"]).default("true"),
+ LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS: z.coerce.number().default(86400), // 24 hours
LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("true"),
- LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.coerce.number().default(300),
+ LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.coerce.number().default(300), // 5 minutes
CLICKHOUSE_URL: z.string().url(),
CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),
CLICKHOUSE_DB: z.string().default("default"),
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 1ad9780ec9..f787915da9 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -20,6 +20,7 @@ export * from "./clickhouse/schemaUtils";
export * from "./clickhouse/schema";
export * from "./repositories/definitions";
export * from "../server/ingestion/types";
+export * from "../server/ingestion/modelMatch";
export * from "./ingestion/processEventBatch";
export * from "../server/ingestion/validateAndInflateScore";
export * from "./redis/redis";
diff --git a/worker/src/services/modelMatch.ts b/packages/shared/src/server/ingestion/modelMatch.ts
similarity index 82%
rename from worker/src/services/modelMatch.ts
rename to packages/shared/src/server/ingestion/modelMatch.ts
index 90faacea50..ab1da312cf 100644
--- a/worker/src/services/modelMatch.ts
+++ b/packages/shared/src/server/ingestion/modelMatch.ts
@@ -1,13 +1,15 @@
-import { Model, Prisma } from "@langfuse/shared";
+import { Model, Prisma } from "../../";
import {
instrumentAsync,
logger,
recordIncrement,
-} from "@langfuse/shared/src/server";
-import { env } from "../env";
-import { redis } from "@langfuse/shared/src/server";
+ redis,
+ safeMultiDel,
+} from "../";
+import { type Cluster } from "ioredis";
+import { env } from "../../env";
import { Decimal } from "decimal.js";
-import { prisma } from "@langfuse/shared/src/db";
+import { prisma } from "../../db";
export type ModelMatchProps = {
projectId: string;
@@ -178,6 +180,11 @@ export const getRedisModelKey = (p: ModelMatchProps) => {
};
const getModelMatchKeyPrefix = () => {
+ if (env.REDIS_CLUSTER_ENABLED === "true") {
+ // Use hash tags for Redis cluster compatibility
+ // This ensures all model cache keys are placed on the same hash slot
+ return "{model-match}";
+ }
return "model-match";
};
@@ -205,3 +212,35 @@ export const redisModelToPrismaModel = (redisModel: string): Model => {
: null,
};
};
+
+export async function clearModelCacheForProject(
+ projectId: string,
+): Promise<void> {
+ if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "false" || !redis) {
+ return;
+ }
+
+ try {
+ const pattern = `${getModelMatchKeyPrefix()}:${projectId}:*`;
+
+ const keys =
+ env.REDIS_CLUSTER_ENABLED === "true"
+ ? (
+ await Promise.all(
+ (redis as Cluster)
+ .nodes("master")
+ .map((node) => node.keys(pattern) || []),
+ )
+ ).flat()
+ : await redis.keys(pattern);
+
+ if (keys.length > 0) {
+ await safeMultiDel(redis, keys);
+ logger.info(
+ `Cleared ${keys.length} model cache entries for project ${projectId}`,
+ );
+ }
+ } catch (error) {
+ logger.error(`Error clearing model cache for project ${projectId}`, error);
+ }
+}
diff --git a/web/src/pages/api/public/models/index.ts b/web/src/pages/api/public/models/index.ts
index 5aaa71243b..baf3f2b82f 100644
--- a/web/src/pages/api/public/models/index.ts
+++ b/web/src/pages/api/public/models/index.ts
@@ -1,5 +1,6 @@
import { prisma } from "@langfuse/shared/src/db";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { clearModelCacheForProject } from "@langfuse/shared/src/server";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import {
GetModelsV1Query,
@@ -130,6 +131,9 @@ export default withMiddlewares({
return createdModel;
});
+ // Clear model cache for the project after successful creation
+ await clearModelCacheForProject(auth.scope.projectId);
+
return prismaToApiModelDefinition({
...model,
Price: (["inputPrice", "outputPrice", "totalPrice"] as const)
diff --git a/web/src/server/api/routers/models.ts b/web/src/server/api/routers/models.ts
index b72fbb2385..f20be506e4 100644
--- a/web/src/server/api/routers/models.ts
+++ b/web/src/server/api/routers/models.ts
@@ -14,7 +14,10 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { ModelUsageUnit, paginationZod } from "@langfuse/shared";
-import { queryClickhouse } from "@langfuse/shared/src/server";
+import {
+ clearModelCacheForProject,
+ queryClickhouse,
+} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
const ModelAllOptions = z.object({
@@ -221,7 +224,7 @@ export const modelRouter = createTRPCRouter({
const modelId = providedModelId ?? uuidv4();
- return await ctx.prisma.$transaction(async (tx) => {
+ const result = await ctx.prisma.$transaction(async (tx) => {
// Check whether model belongs to project
// This check is important to prevent users from updating prices for models that they do not have access to
const existingModel = await tx.model.findUnique({
@@ -308,6 +311,11 @@ export const modelRouter = createTRPCRouter({
return upsertedModel;
});
+
+ // Clear model cache for the project after successful upsert
+ await clearModelCacheForProject(projectId);
+
+ return result;
}),
delete: protectedProjectProcedure
.input(
diff --git a/worker/src/__tests__/modelMatch.test.ts b/worker/src/__tests__/modelMatch.test.ts
index 8a0f1a976e..6f334ad0dd 100644
--- a/worker/src/__tests__/modelMatch.test.ts
+++ b/worker/src/__tests__/modelMatch.test.ts
@@ -1,11 +1,12 @@
import { expect, describe, it, beforeEach, afterEach } from "vitest";
import { prisma } from "@langfuse/shared/src/db";
-import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { createOrgProjectAndApiKey, redis } from "@langfuse/shared/src/server";
import {
findModel,
findModelInPostgres,
getRedisModelKey,
-} from "../services/modelMatch";
+ clearModelCacheForProject,
+} from "@langfuse/shared/src/server";
describe("modelMatch", () => {
describe("findModel", () => {
@@ -162,4 +163,75 @@ describe("modelMatch", () => {
expect(result).toBeNull();
});
});
+
+ describe("clearModelCacheForProject", () => {
+ it("should clear all cached models for a project", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create and cache multiple models
+ await prisma.model.create({
+ data: {
+ projectId,
+ modelName: "gpt-4",
+ matchPattern: "gpt-4",
+ unit: "TOKENS",
+ inputPrice: "1.0",
+ },
+ });
+
+ await prisma.model.create({
+ data: {
+ projectId,
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "gpt-3.5-turbo",
+ unit: "TOKENS",
+ inputPrice: "0.5",
+ },
+ });
+
+ // Cache both models by finding them
+ await findModel({ projectId, model: "gpt-4" });
+ await findModel({ projectId, model: "gpt-3.5-turbo" });
+
+ // Verify models are cached in Redis
+ const redisKey1 = getRedisModelKey({ projectId, model: "gpt-4" });
+ const redisKey2 = getRedisModelKey({ projectId, model: "gpt-3.5-turbo" });
+
+ const cachedModel1 = await redis?.get(redisKey1);
+ const cachedModel2 = await redis?.get(redisKey2);
+
+ expect(cachedModel1).not.toBeNull();
+ expect(cachedModel2).not.toBeNull();
+
+ // Clear the cache for the project
+ await clearModelCacheForProject(projectId);
+
+ // Verify models are no longer cached
+ const clearedModel1 = await redis?.get(redisKey1);
+ const clearedModel2 = await redis?.get(redisKey2);
+
+ expect(clearedModel1).toBeNull();
+ expect(clearedModel2).toBeNull();
+ });
+
+ it("should clear cached not-found tokens for a project", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const nonExistentModel = "nonexistent-model";
+
+ // Cache a not-found result
+ await findModel({ projectId, model: nonExistentModel });
+
+ // Verify the not-found token is cached
+ const redisKey = getRedisModelKey({ projectId, model: nonExistentModel });
+ const cachedValue = await redis?.get(redisKey);
+ expect(cachedValue).toBe("LANGFUSE_MODEL_MATCH_NOT_FOUND");
+
+ // Clear the cache for the project
+ await clearModelCacheForProject(projectId);
+
+ // Verify the not-found token is cleared
+ const clearedValue = await redis?.get(redisKey);
+ expect(clearedValue).toBeNull();
+ });
+ });
});
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 65ec921628..8c32a6d6ad 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -128,9 +128,6 @@ const EnvSchema = z.object({
.enum(["true", "false"])
.default("false"),
- LANGFUSE_CACHE_MODEL_MATCH_ENABLED: z.enum(["true", "false"]).default("true"),
- LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS: z.coerce.number().default(30),
-
// Flags to toggle queue consumers on or off.
QUEUE_CONSUMER_CLOUD_USAGE_METERING_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 532ef20609..b9dfe1ade5 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -30,6 +30,7 @@ import {
traceRecordReadSchema,
TraceUpsertQueue,
UsageCostType,
+ findModel,
validateAndInflateScore,
convertObservationToTraceMt,
convertTraceToTraceMt,
@@ -47,7 +48,6 @@ import {
} from "./utils";
import { randomUUID } from "crypto";
import { env } from "../../env";
-import { findModel } from "../modelMatch";
import { SpanKind } from "@opentelemetry/api";
import { ClickhouseReadSkipCache } from "../../utils/clickhouseReadSkipCache";