🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(cache): add local l1 cache for model match (#12977)
Hassieb Pakzad7d15ee9ed4da
diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.mdindex d6b62b611d..8657234a8d 100644--- a/packages/shared/AGENTS.md+++ b/packages/shared/AGENTS.md@@ -25,6 +25,7 @@ Use root [AGENTS.md](../../AGENTS.md) for monorepo-level rules.- Main exports: `src/index.ts`- DB clients and types: `src/db.ts`- Server exports: `src/server/index.ts`+- Server cache utilities: `src/server/cache/*`- Domain model types: `src/domain/*`- Repository layer: `src/server/repositories/*`- Queue payload schemas: `src/server/queues.ts`diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex b4ce6a55ed..e9e9b70297 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -112,6 +112,7 @@"langfuse-langchain": "3.38.20","lodash": "^4.18.1","lossless-json": "^4.1.1",+ "lru-cache": "^11.2.7","next-auth": "^4.24.13","nodemailer": "^7.0.11","oci-objectstorage": "^2.125.0",diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex d90959955c..7e452113d5 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -57,6 +57,18 @@ const EnvSchema = z.object({.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_LOCAL_CACHE_MODEL_MATCH_ENABLED: z+ .enum(["true", "false"])+ .default("false"),+ LANGFUSE_LOCAL_CACHE_MODEL_MATCH_TTL_MS: z.coerce+ .number()+ .positive()+ .default(10_000),+ LANGFUSE_LOCAL_CACHE_MODEL_MATCH_MAX: z.coerce+ .number()+ .int()+ .positive()+ .default(20_000),LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("true"),LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.coerce.number().default(3600), // 1hCLICKHOUSE_URL: z.string().url(),diff --git a/packages/shared/src/server/cache/index.ts b/packages/shared/src/server/cache/index.tsnew file mode 100644index 0000000000..9855312d9d--- /dev/null+++ b/packages/shared/src/server/cache/index.ts@@ -0,0 +1 @@+export * from "./localCache";diff --git a/packages/shared/src/server/cache/localCache.ts b/packages/shared/src/server/cache/localCache.tsnew file mode 100644index 0000000000..08d50eb4a9--- /dev/null+++ b/packages/shared/src/server/cache/localCache.ts@@ -0,0 +1,172 @@+import { LRUCache } from "lru-cache";+import { logger } from "../logger";+import { recordGauge, recordIncrement } from "../instrumentation";++export type LocalCacheLoadResult<V> = {+ value: V | undefined;+ ttlMs?: number;+ source?: string;+};++export type LocalCacheConfig = {+ namespace: string;+ enabled: boolean;+ ttlMs: number;+ max: number;+};++export class LocalCache<V extends {}> {+ private readonly config: LocalCacheConfig;+ private readonly cache: LRUCache<string, V>;++ constructor(config: LocalCacheConfig) {+ this.config = config;+ const dispose: LRUCache.Disposer<string, V> = (_value, _key, reason) => {+ if (reason === "evict") {+ this.record("evict");+ this.recordSizeMetrics();+ }+ };++ const baseOptions = {+ ttlAutopurge: false as const,+ allowStale: false as const,+ updateAgeOnGet: false as const,+ updateAgeOnHas: false as const,+ dispose,+ };++ this.cache = new LRUCache<string, V>({+ ...baseOptions,+ ttl: config.ttlMs,+ max: config.max,+ });+ this.logInfo("Initialized local cache", {+ enabled: config.enabled,+ ttlMs: config.ttlMs,+ max: config.max,+ });+ }++ get(key: string): V | undefined {+ if (!this.config.enabled) {+ return undefined;+ }++ const value = this.cache.get(key);+ this.record(value === undefined ? "miss" : "hit");+ this.logDebug(+ value === undefined ? "Local cache miss" : "Local cache hit",+ {+ size: this.cache.size,+ keyLength: key.length,+ },+ );++ return value;+ }++ set(key: string, value: V): void {+ if (!this.config.enabled) {+ return;+ }++ const ttlMs = this.config.ttlMs;++ try {+ this.cache.set(key, value, { ttl: ttlMs });+ this.record("set");+ this.recordSizeMetrics();+ this.logDebug("Stored local cache entry", {+ ttlMs,+ size: this.cache.size,+ keyLength: key.length,+ });+ } catch (error) {+ logger.error(+ `Failed to set local cache entry for namespace ${this.config.namespace}`,+ error,+ );+ }+ }++ clear(): void {+ this.cache.clear();+ this.record("clear");+ this.recordSizeMetrics();+ this.logDebug("Cleared local cache");+ }++ async getOrLoad(+ key: string,+ loader: () => Promise<LocalCacheLoadResult<V>>,+ ): Promise<LocalCacheLoadResult<V>> {+ const cached = this.get(key);+ if (cached !== undefined) {+ return { value: cached, source: "local" };+ }++ if (!this.config.enabled) {+ this.logDebug("Bypassing disabled local cache", {+ keyLength: key.length,+ });+ return loader();+ }++ const result = await loader();+ this.logDebug("Completed local cache load", {+ source: result.source ?? "unknown",+ cacheable: result.value !== undefined,+ ttlMs: result.ttlMs ?? null,+ keyLength: key.length,+ });++ if (result.value !== undefined) {+ this.set(key, result.value);+ }++ return result;+ }++ private record(metric: string): void {+ recordIncrement(`langfuse.local_cache.${metric}`, 1, {+ namespace: this.config.namespace,+ });+ }++ private recordSizeMetrics(): void {+ recordGauge("langfuse.local_cache.size_entries", this.cache.size, {+ namespace: this.config.namespace,+ });+ }++ private logDebug(message: string, metadata?: Record<string, unknown>): void {+ if (!logger.isLevelEnabled("debug")) {+ return;+ }++ const formattedMetadata =+ metadata === undefined ? "" : ` ${safeSerialize(metadata)}`;++ logger.debug(+ `[LocalCache:${this.config.namespace}] ${message}${formattedMetadata}`,+ );+ }++ private logInfo(message: string, metadata?: Record<string, unknown>): void {+ const formattedMetadata =+ metadata === undefined ? "" : ` ${safeSerialize(metadata)}`;++ logger.info(+ `[LocalCache:${this.config.namespace}] ${message}${formattedMetadata}`,+ );+ }+}++const safeSerialize = (value: unknown): string => {+ try {+ return JSON.stringify(value);+ } catch {+ return "[unserializable]";+ }+};diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 7761fb7055..0a878ca1e5 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -1,4 +1,5 @@export * from "./services/StorageService";+export * from "./cache";export * from "./services/BufferedStreamUploader";export * from "./services/S3ChunkedUploadStrategy";export * from "./services/email/organizationInvitation/sendMembershipInvitationEmail";diff --git a/packages/shared/src/server/ingestion/modelMatch.ts b/packages/shared/src/server/ingestion/modelMatch.tsindex 36c97d68c0..7a1edd4373 100644--- a/packages/shared/src/server/ingestion/modelMatch.ts+++ b/packages/shared/src/server/ingestion/modelMatch.ts@@ -8,6 +8,7 @@ import {safeMultiDel,scanKeys,} from "../";+import { LocalCache } from "../cache";import { env } from "../../env";import { Decimal } from "decimal.js";import { prisma } from "../../db";@@ -24,6 +25,22 @@ export type ModelWithPrices = {};const MODEL_MATCH_CACHE_LOCKED_KEY = "LOCK:model-match-clear";+const DEFAULT_LOCAL_CACHE_MODEL_MATCH_TTL_MS = 10_000;+const DEFAULT_LOCAL_CACHE_MODEL_MATCH_MAX = 20_000;+// This L1 cache is intentionally TTL-only. Cross-container consistency continues+// to come from Redis invalidation plus the short local TTL.+const modelMatchLocalCache = new LocalCache<ModelWithPrices>({+ namespace: "model_match",+ enabled: env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_ENABLED === "true",+ ttlMs: getPositiveNumberOrDefault(+ env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_TTL_MS,+ DEFAULT_LOCAL_CACHE_MODEL_MATCH_TTL_MS,+ ),+ max: getPositiveNumberOrDefault(+ env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_MAX,+ DEFAULT_LOCAL_CACHE_MODEL_MATCH_MAX,+ ),+});export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {return instrumentAsync(@@ -33,66 +50,132 @@ export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {},async (span) => {if (logger.isLevelEnabled("debug")) {- logger.debug(`Finding model for ${JSON.stringify(p)}`);+ logger.debug(+ formatModelMatchDebugMessage("Resolving model match", {+ projectId: p.projectId,+ model: p.model,+ localCacheEnabled:+ env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_ENABLED === "true",+ redisCacheEnabled:+ env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true",+ }),+ );}- const cachedResult = await getModelWithPricesFromRedis(p);- if (cachedResult) {- span.setAttribute("model_match_source", "redis");+ const localCacheKey = getRedisModelKey(p);+ const { source, value } = await modelMatchLocalCache.getOrLoad(+ localCacheKey,+ async () => {+ const cachedResult = await getModelWithPricesFromRedis(p);+ if (cachedResult) {+ return {+ value: cachedResult,+ source: "redis",+ };+ }++ const postgresModel = await findModelInPostgres(p);+ if (postgresModel) {+ const pricingTiers = await findPricingTiersForModel(+ postgresModel.id,+ );++ if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {+ await addModelWithPricingTiersToRedis(+ p,+ postgresModel,+ pricingTiers,+ );+ }++ return {+ value: { model: postgresModel, pricingTiers },+ source: "postgres",+ };+ }++ if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {+ await addModelNotFoundTokenToRedis(p);+ }++ return {+ value: { model: null, pricingTiers: [] },+ source: "none",+ };+ },+ );- if (cachedResult.model === null) {- return { model: null, pricingTiers: [] };- } else {+ if (!value || value.model === null) {+ span.setAttribute("model_match_source", source ?? "none");+ if (+ source === "none" &&+ env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true"+ ) {+ span.setAttribute("model_cache_set", "true");+ }++ if (logger.isLevelEnabled("debug")) {logger.debug(- `Found model name ${cachedResult.model?.modelName} (id: ${cachedResult.model?.id}) for project ${p.projectId} and model ${p.model}`,+ formatModelMatchDebugMessage(+ "Model match resolved without a model",+ {+ projectId: p.projectId,+ model: p.model,+ source: source ?? "none",+ pricingTierCount: 0,+ },+ ),);- span.setAttribute("matched_model_id", cachedResult.model.id);}- return cachedResult;+ return { model: null, pricingTiers: [] };}- // try to find model in Postgres- const postgresModel = await findModelInPostgres(p);-- if (postgresModel && env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {- const pricingTiers = await findPricingTiersForModel(postgresModel.id);- await addModelWithPricingTiersToRedis(p, postgresModel, pricingTiers);-- span.setAttribute("matched_model_id", postgresModel.id);- span.setAttribute("model_match_source", "postgres");- span.setAttribute("model_cache_set", "true");-- logger.debug(- `Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,- );- return { model: postgresModel, pricingTiers };- } else if (postgresModel) {- const pricingTiers = await findPricingTiersForModel(postgresModel.id);- span.setAttribute("matched_model_id", postgresModel.id);- span.setAttribute("model_match_source", "postgres");- span.setAttribute("model_cache_set", "false");-- logger.debug(- `Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,+ span.setAttribute("model_match_source", source ?? "unknown");+ span.setAttribute("matched_model_id", value.model.id);+ if (source === "postgres") {+ span.setAttribute(+ "model_cache_set",+ String(env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true"),);- return { model: postgresModel, pricingTiers };- } else {- span.setAttribute("model_match_source", "none");-- if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {- await addModelNotFoundTokenToRedis(p);- span.setAttribute("model_cache_set", "true");- }+ }+ if (logger.isLevelEnabled("debug")) {logger.debug(- `Model not found for project ${p.projectId} and model ${p.model}`,+ formatModelMatchDebugMessage("Model match resolved", {+ projectId: p.projectId,+ model: p.model,+ source: source ?? "unknown",+ matchedModelId: value.model.id,+ matchedModelName: value.model.modelName,+ pricingTierCount: value.pricingTiers.length,+ }),);- return { model: null, pricingTiers: [] };}+ return value;},);}+const formatModelMatchDebugMessage = (+ message: string,+ metadata: Record<string, unknown>,+): string => {+ try {+ return `${message} ${JSON.stringify(metadata)}`;+ } catch {+ return `${message} [unserializable]`;+ }+};++function getPositiveNumberOrDefault(value: unknown, fallback: number): number {+ const parsed = Number(value);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;+}++export const clearModelMatchLocalCache = (): void => {+ modelMatchLocalCache.clear();+};+const getModelWithPricesFromRedis = async (p: ModelMatchProps,): Promise<ModelWithPrices | null> => {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2973719a3a..2114fe61c9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -241,6 +241,9 @@ importers:lossless-json:specifier: ^4.1.1version: 4.1.1+ lru-cache:+ specifier: ^11.2.7+ version: 11.2.7next-auth:specifier: ^4.24.13version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])@@ -8235,6 +8238,10 @@ packages:resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}+ resolution: {integrity: sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==}+ engines: {node: 20 || >=22}+resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}@@ -19571,6 +19578,8 @@ snapshots:+ [email protected]: {}+dependencies:yallist: 3.1.1diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 02fdb2414f..2fde58578e 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -316,10 +316,10 @@ export class ApiAuthService {// add the key to redis for future use if available, this does not throw// only do so if the new hashkey exists already.if (apiKeyAndOrganisation && apiKeyAndOrganisation.fastHashedSecretKey) {- await this.addApiKeyToRedis(- hash,- this.convertToRedisRepresentation(apiKeyAndOrganisation),+ const cachedApiKey = this.convertToRedisRepresentation(+ apiKeyAndOrganisation,);+ await this.addApiKeyToRedis(hash, cachedApiKey);}return apiKeyAndOrganisation? this.convertToRedisRepresentation(apiKeyAndOrganisation)diff --git a/worker/src/__tests__/localCache.test.ts b/worker/src/__tests__/localCache.test.tsnew file mode 100644index 0000000000..6148a8bc89--- /dev/null+++ b/worker/src/__tests__/localCache.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it, vi } from "vitest";+import { LocalCache } from "../../../packages/shared/src/server";++describe("LocalCache", () => {+ it("should expire entries after ttl", async () => {+ const cache = new LocalCache<{ value: string }>({+ namespace: "test",+ enabled: true,+ ttlMs: 50,+ max: 10,+ });++ cache.set("entry", { value: "cached" });+ expect(cache.get("entry")).toEqual({ value: "cached" });++ await new Promise((resolve) => setTimeout(resolve, 75));++ expect(cache.get("entry")).toBeUndefined();+ });++ it("should load and cache uncached values", async () => {+ const cache = new LocalCache<{ value: string }>({+ namespace: "test",+ enabled: true,+ ttlMs: 1000,+ max: 10,+ });++ const loader = vi.fn(async () => ({+ value: { value: "loaded" },+ source: "loader",+ }));++ const result = await cache.getOrLoad("entry", loader);++ expect(result.value).toEqual({ value: "loaded" });+ expect(loader).toHaveBeenCalledTimes(1);+ expect(cache.get("entry")).toEqual({ value: "loaded" });+ });++ it("should bypass reads and writes when disabled", () => {+ const cache = new LocalCache<{ value: string }>({+ namespace: "test",+ enabled: false,+ ttlMs: 1000,+ max: 10,+ });++ cache.set("entry", { value: "cached" });++ expect(cache.get("entry")).toBeUndefined();+ });+});diff --git a/worker/src/__tests__/modelMatch.test.ts b/worker/src/__tests__/modelMatch.test.tsindex d197cd477d..37db7c9c27 100644--- a/worker/src/__tests__/modelMatch.test.ts+++ b/worker/src/__tests__/modelMatch.test.ts@@ -1,15 +1,62 @@-import { expect, describe, it } from "vitest";-import { prisma } from "@langfuse/shared/src/db";-import { createOrgProjectAndApiKey, redis } from "@langfuse/shared/src/server";import {- findModel,- findModelInPostgres,- getRedisModelKey,- clearModelCacheForProject,-} from "@langfuse/shared/src/server";+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import { prisma } from "../../../packages/shared/src/db";import { v4 as uuidv4 } from "uuid";+type SharedServerModule = typeof import("../../../packages/shared/src/server");++let createOrgProjectAndApiKey: SharedServerModule["createOrgProjectAndApiKey"];+let redis: SharedServerModule["redis"];+let clearModelMatchLocalCache: SharedServerModule["clearModelMatchLocalCache"];+let findModel: SharedServerModule["findModel"];+let findModelInPostgres: SharedServerModule["findModelInPostgres"];+let getRedisModelKey: SharedServerModule["getRedisModelKey"];+let clearModelCacheForProject: SharedServerModule["clearModelCacheForProject"];++const originalLocalCacheSetting =+ process.env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_ENABLED;+describe("modelMatch", () => {+ beforeAll(async () => {+ process.env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_ENABLED = "true";+ vi.resetModules();++ const sharedServer: SharedServerModule =+ await import("../../../packages/shared/src/server");++ ({+ createOrgProjectAndApiKey,+ redis,+ clearModelMatchLocalCache,+ findModel,+ findModelInPostgres,+ getRedisModelKey,+ clearModelCacheForProject,+ } = sharedServer);+ });++ afterAll(() => {+ if (originalLocalCacheSetting === undefined) {+ delete process.env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_ENABLED;+ } else {+ process.env.LANGFUSE_LOCAL_CACHE_MODEL_MATCH_ENABLED =+ originalLocalCacheSetting;+ }++ vi.resetModules();+ });++ beforeEach(() => {+ clearModelMatchLocalCache();+ });+describe("findModel", () => {it("should return model with prices from Redis if available", async () => {const { projectId } = await createOrgProjectAndApiKey();@@ -47,7 +94,7 @@ describe("modelMatch", () => {model: "gpt-4",});- // Now find it again - should come from Redis+ // Now find it again - it should come from cache without changing the resultconst result = await findModel({projectId,model: "gpt-4",@@ -144,6 +191,51 @@ describe("modelMatch", () => {const cachedValue = await redis?.get(redisKey);expect(cachedValue).toBe("LANGFUSE_MODEL_MATCH_NOT_FOUND");});++ it("should serve models from the local cache after the Redis entry is deleted", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const model = await prisma.model.create({+ data: {+ projectId,+ modelName: "gpt-4o",+ matchPattern: "gpt-4o",+ unit: "TOKENS",+ },+ });++ await findModel({ projectId, model: "gpt-4o" });++ const redisKey = getRedisModelKey({ projectId, model: "gpt-4o" });+ await redis?.del(redisKey);++ const result = await findModel({ projectId, model: "gpt-4o" });++ expect(result.model?.id).toBe(model.id);+ expect(await redis?.get(redisKey)).toBeNull();+ });++ it("should locally cache not-found models for a short time", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const modelName = "new-model-after-cache";++ await findModel({ projectId, model: modelName });++ const redisKey = getRedisModelKey({ projectId, model: modelName });+ await redis?.del(redisKey);++ await prisma.model.create({+ data: {+ projectId,+ modelName,+ matchPattern: modelName,+ unit: "TOKENS",+ },+ });++ const result = await findModel({ projectId, model: modelName });++ expect(result.model).toBeNull();+ });});describe("findModelInPostgres", () => {