[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M752H62NQWPZ2PH6ETZGWVJD":3,"skill-same:01M752H62NQWPZ2PH6ETZGWVJD":49},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":5,"forksCount":14,"repositoryHtmlUrl":31,"repositoryHomepageUrl":6,"ownerHtmlUrl":32,"ownerBlogUrl":33,"ownerDescription":6,"updatedAt":34,"install":35,"resources":48},"01M752H62NQWPZ2PH6ETZGWVJD","langfuse-performance-tuning",null,"Optimize Langfuse tracing performance for high-throughput applications.\nUse when experiencing latency issues, optimizing trace overhead,\nor scaling Langfuse for production workloads.\nTrigger with phrases like \"langfuse performance\", \"optimize langfuse\",\n\"langfuse latency\", \"langfuse overhead\", \"langfuse slow\".","SamuelChien\u002Fmega-skills-collection","SamuelChien","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4652114?v=4","01M74KK34WVHA0P5ZYSJRDDFMG","Samuel Chien","01M74KK35FQN1N9VZ9EPTH3P2S",0,"MIT","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Flangfuse-performance-tuning\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: langfuse-performance-tuning\ndescription: |\n  Optimize Langfuse tracing performance for high-throughput applications.\n  Use when experiencing latency issues, optimizing trace overhead,\n  or scaling Langfuse for production workloads.\n  Trigger with phrases like \"langfuse performance\", \"optimize langfuse\",\n  \"langfuse latency\", \"langfuse overhead\", \"langfuse slow\".\nallowed-tools: Read, Write, Edit\nversion: 1.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ncompatible-with: claude-code, codex, openclaw\n---\n# Langfuse Performance Tuning\n\n## Overview\nOptimize Langfuse tracing for minimal overhead and maximum throughput.\n\n## Prerequisites\n- Existing Langfuse integration\n- Performance baseline measurements\n- Understanding of async patterns\n\n## Performance Targets\n\n| Metric | Target | Critical |\n|--------|--------|----------|\n| Trace creation overhead | \u003C 1ms | \u003C 5ms |\n| Flush latency | \u003C 100ms | \u003C 500ms |\n| Memory per trace | \u003C 1KB | \u003C 5KB |\n| CPU overhead | \u003C 1% | \u003C 5% |\n\n## Instructions\n\n### Step 1: Measure Baseline Performance\n\n```typescript\n\u002F\u002F scripts\u002Fbenchmark-langfuse.ts\nimport { Langfuse } from \"langfuse\";\nimport { performance } from \"perf_hooks\";\n\nasync function benchmark() {\n  const langfuse = new Langfuse();\n  const iterations = 1000;  # 1000: 1 second in ms\n\n  \u002F\u002F Measure trace creation\n  const traceTimings: number[] = [];\n  for (let i = 0; i \u003C iterations; i++) {\n    const start = performance.now();\n    const trace = langfuse.trace({ name: `benchmark-${i}` });\n    traceTimings.push(performance.now() - start);\n  }\n\n  \u002F\u002F Measure generation creation\n  const genTimings: number[] = [];\n  const trace = langfuse.trace({ name: \"gen-benchmark\" });\n  for (let i = 0; i \u003C iterations; i++) {\n    const start = performance.now();\n    const gen = trace.generation({\n      name: `gen-${i}`,\n      model: \"gpt-4\",\n      input: [{ role: \"user\", content: \"test\" }],\n    });\n    gen.end({ output: \"response\" });\n    genTimings.push(performance.now() - start);\n  }\n\n  \u002F\u002F Measure flush\n  const flushStart = performance.now();\n  await langfuse.flushAsync();\n  const flushTime = performance.now() - flushStart;\n\n  \u002F\u002F Calculate stats\n  const stats = (arr: number[]) => ({\n    mean: arr.reduce((a, b) => a + b) \u002F arr.length,\n    p50: arr.sort((a, b) => a - b)[Math.floor(arr.length * 0.5)],\n    p95: arr.sort((a, b) => a - b)[Math.floor(arr.length * 0.95)],\n    p99: arr.sort((a, b) => a - b)[Math.floor(arr.length * 0.99)],\n  });\n\n  console.log(\"=== Langfuse Performance Benchmark ===\");\n  console.log(`\\nTrace Creation (${iterations} iterations):`);\n  console.log(JSON.stringify(stats(traceTimings), null, 2));\n  console.log(`\\nGeneration Creation (${iterations} iterations):`);\n  console.log(JSON.stringify(stats(genTimings), null, 2));\n  console.log(`\\nFlush Time: ${flushTime.toFixed(2)}ms`);\n\n  await langfuse.shutdownAsync();\n}\n\nbenchmark();\n```\n\n### Step 2: Optimize Batching Configuration\n\n```typescript\n\u002F\u002F High-throughput configuration\nconst langfuse = new Langfuse({\n  publicKey: process.env.LANGFUSE_PUBLIC_KEY!,\n  secretKey: process.env.LANGFUSE_SECRET_KEY!,\n\n  \u002F\u002F Batching optimization\n  flushAt: 100,           \u002F\u002F Larger batches = fewer requests\n  flushInterval: 10000,   \u002F\u002F Less frequent flushes  # 10000: 10 seconds in ms\n\n  \u002F\u002F Timeout tuning\n  requestTimeout: 30000,  \u002F\u002F Allow time for large batches  # 30000: 30 seconds in ms\n\n  \u002F\u002F Optional: Disable in development\n  enabled: process.env.NODE_ENV === \"production\",\n});\n```\n\n### Step 3: Implement Non-Blocking Tracing\n\n```typescript\n\u002F\u002F Trace wrapper that never blocks the main operation\nclass NonBlockingLangfuse {\n  private langfuse: Langfuse;\n  private errorCount = 0;\n  private maxErrors = 10;\n\n  constructor(config: ConstructorParameters\u003Ctypeof Langfuse>[0]) {\n    this.langfuse = new Langfuse(config);\n  }\n\n  \u002F\u002F Fire-and-forget trace\n  trace(params: Parameters\u003Ctypeof this.langfuse.trace>[0]) {\n    if (this.errorCount >= this.maxErrors) {\n      \u002F\u002F Circuit breaker: stop tracing if too many errors\n      return this.createNoOpTrace();\n    }\n\n    try {\n      return this.langfuse.trace(params);\n    } catch (error) {\n      this.errorCount++;\n      console.error(\"Langfuse trace error:\", error);\n      return this.createNoOpTrace();\n    }\n  }\n\n  private createNoOpTrace() {\n    return {\n      id: \"noop\",\n      span: () => this.createNoOpSpan(),\n      generation: () => this.createNoOpGeneration(),\n      update: () => {},\n      getTraceUrl: () => \"\",\n    };\n  }\n\n  private createNoOpSpan() {\n    return {\n      id: \"noop\",\n      span: () => this.createNoOpSpan(),\n      generation: () => this.createNoOpGeneration(),\n      end: () => {},\n    };\n  }\n\n  private createNoOpGeneration() {\n    return {\n      id: \"noop\",\n      end: () => {},\n    };\n  }\n\n  \u002F\u002F Background flush - don't await in hot path\n  flush() {\n    this.langfuse.flushAsync().catch((error) => {\n      this.errorCount++;\n      console.error(\"Langfuse flush error:\", error);\n    });\n  }\n\n  async shutdown() {\n    return this.langfuse.shutdownAsync();\n  }\n}\n```\n\n### Step 4: Optimize Data Payload Size\n\n```typescript\n\u002F\u002F Reduce trace payload size\nfunction optimizeTraceInput(input: any): any {\n  \u002F\u002F Truncate large strings\n  const MAX_STRING_LENGTH = 10000;  # 10000: 10 seconds in ms\n\n  if (typeof input === \"string\") {\n    return input.length > MAX_STRING_LENGTH\n      ? input.slice(0, MAX_STRING_LENGTH) + \"...[truncated]\"\n      : input;\n  }\n\n  if (Array.isArray(input)) {\n    \u002F\u002F Limit array size\n    const MAX_ARRAY_LENGTH = 100;\n    const truncated = input.slice(0, MAX_ARRAY_LENGTH);\n    return truncated.map(optimizeTraceInput);\n  }\n\n  if (typeof input === \"object\" && input !== null) {\n    \u002F\u002F Remove large binary data\n    const optimized: Record\u003Cstring, any> = {};\n    for (const [key, value] of Object.entries(input)) {\n      if (value instanceof Buffer || value instanceof Uint8Array) {\n        optimized[key] = `[Binary: ${value.length} bytes]`;\n      } else {\n        optimized[key] = optimizeTraceInput(value);\n      }\n    }\n    return optimized;\n  }\n\n  return input;\n}\n\n\u002F\u002F Use in traces\nconst trace = langfuse.trace({\n  name: \"optimized-trace\",\n  input: optimizeTraceInput(largeInput),\n});\n```\n\n### Step 5: Implement Sampling for Ultra-High Volume\n\n```typescript\ninterface SamplingStrategy {\n  shouldSample(params: TraceParams): boolean;\n}\n\n\u002F\u002F Deterministic sampling based on trace attributes\nclass DeterministicSampler implements SamplingStrategy {\n  private rate: number;\n\n  constructor(rate: number) {\n    this.rate = rate;\n  }\n\n  shouldSample(params: TraceParams): boolean {\n    \u002F\u002F Always sample errors\n    if (params.level === \"ERROR\" || params.tags?.includes(\"error\")) {\n      return true;\n    }\n\n    \u002F\u002F Deterministic hash-based sampling\n    const hash = this.hashString(params.name + (params.userId || \"\"));\n    return (hash % 100) \u003C (this.rate * 100);\n  }\n\n  private hashString(str: string): number {\n    let hash = 0;\n    for (let i = 0; i \u003C str.length; i++) {\n      const char = str.charCodeAt(i);\n      hash = ((hash \u003C\u003C 5) - hash) + char;\n      hash = hash & hash;\n    }\n    return Math.abs(hash);\n  }\n}\n\n\u002F\u002F Adaptive sampling based on throughput\nclass AdaptiveSampler implements SamplingStrategy {\n  private windowMs = 60000;  # 60000: 1 minute in ms\n  private maxPerWindow = 1000;  # 1000: 1 second in ms\n  private counts: number[] = [];\n\n  shouldSample(params: TraceParams): boolean {\n    const now = Date.now();\n    const windowStart = now - this.windowMs;\n\n    \u002F\u002F Clean old counts\n    this.counts = this.counts.filter((t) => t > windowStart);\n\n    \u002F\u002F Check if under limit\n    if (this.counts.length \u003C this.maxPerWindow) {\n      this.counts.push(now);\n      return true;\n    }\n\n    \u002F\u002F Over limit - only sample important traces\n    return params.level === \"ERROR\";\n  }\n}\n\n\u002F\u002F Apply sampling\nconst sampler = new DeterministicSampler(0.1); \u002F\u002F 10% sampling\n\nfunction sampledTrace(params: TraceParams) {\n  if (!sampler.shouldSample(params)) {\n    return createNoOpTrace();\n  }\n\n  return langfuse.trace({\n    ...params,\n    metadata: {\n      ...params.metadata,\n      sampled: true,\n    },\n  });\n}\n```\n\n### Step 6: Memory Management\n\n```typescript\n\u002F\u002F Prevent memory leaks with trace cleanup\nclass ManagedLangfuse {\n  private langfuse: Langfuse;\n  private activeTraces: Map\u003Cstring, { createdAt: Date }> = new Map();\n  private maxTraceAge = 300000; \u002F\u002F 5 minutes  # 300000 = configured value\n\n  constructor(config: ConstructorParameters\u003Ctypeof Langfuse>[0]) {\n    this.langfuse = new Langfuse(config);\n\n    \u002F\u002F Periodic cleanup\n    setInterval(() => this.cleanupStaleTraces(), 60000);  # 60000: 1 minute in ms\n  }\n\n  trace(params: Parameters\u003Ctypeof this.langfuse.trace>[0]) {\n    const trace = this.langfuse.trace(params);\n    this.activeTraces.set(trace.id, { createdAt: new Date() });\n    return trace;\n  }\n\n  private cleanupStaleTraces() {\n    const now = Date.now();\n    let cleaned = 0;\n\n    for (const [id, meta] of this.activeTraces) {\n      if (now - meta.createdAt.getTime() > this.maxTraceAge) {\n        this.activeTraces.delete(id);\n        cleaned++;\n      }\n    }\n\n    if (cleaned > 0) {\n      console.log(`Cleaned up ${cleaned} stale trace references`);\n    }\n  }\n\n  getStats() {\n    return {\n      activeTraces: this.activeTraces.size,\n      heapUsed: process.memoryUsage().heapUsed \u002F 1024 \u002F 1024,  # 1024: 1 KB\n    };\n  }\n}\n```\n\n## Output\n- Baseline performance measurements\n- Optimized batching configuration\n- Non-blocking trace wrapper\n- Payload size optimization\n- Sampling strategies for high volume\n- Memory leak prevention\n\n## Performance Optimization Checklist\n\n| Optimization | Impact | Effort |\n|--------------|--------|--------|\n| Increase `flushAt` | High | Low |\n| Non-blocking traces | High | Medium |\n| Payload truncation | Medium | Low |\n| Sampling | High | Medium |\n| Memory management | Medium | Medium |\n\n## Error Handling\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| High latency | Small batch size | Increase `flushAt` |\n| Memory growth | No cleanup | Add trace cleanup |\n| Request timeouts | Large payloads | Truncate inputs |\n| High CPU | Sync operations | Use async patterns |\n\n## Resources\n- [Langfuse SDK Configuration](https:\u002F\u002Flangfuse.com\u002Fdocs\u002Fsdk)\n- [Node.js Performance](https:\u002F\u002Fnodejs.org\u002Fen\u002Fdocs\u002Fguides\u002Fdont-block-the-event-loop)\n- [Sampling Strategies](https:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Fconcepts\u002Fsampling\u002F)\n\n## Next Steps\nFor cost optimization, see `langfuse-cost-tuning`.\n\n## Examples\n\n**Basic usage**: Apply langfuse performance tuning to a standard project setup with default configuration options.\n\n**Advanced scenario**: Customize langfuse performance tuning for production environments with multiple constraints and team-specific requirements.","# Langfuse Performance Tuning\n\n## Overview\nOptimize Langfuse tracing for minimal overhead and maximum throughput.\n\n## Prerequisites\n- Existing Langfuse integration\n- Performance baseline measurements\n- Understanding of async patterns\n\n## Performance Targets\n\n| Metric | Target | Critical |\n|--------|--------|----------|\n| Trace creation overhead | \u003C 1ms | \u003C 5ms |\n| Flush latency | \u003C 100ms | \u003C 500ms |\n| Memory per trace | \u003C 1KB | \u003C 5KB |\n| CPU overhead | \u003C 1% | \u003C 5% |\n\n## Instructions\n\n### Step 1: Measure Baseline Performance\n\n```typescript\n\u002F\u002F scripts\u002Fbenchmark-langfuse.ts\nimport { Langfuse } from \"langfuse\";\nimport { performance } from \"perf_hooks\";\n\nasync function benchmark() {\n  const langfuse = new Langfuse();\n  const iterations = 1000;  # 1000: 1 second in ms\n\n  \u002F\u002F Measure trace creation\n  const traceTimings: number[] = [];\n  for (let i = 0; i \u003C iterations; i++) {\n    const start = performance.now();\n    const trace = langfuse.trace({ name: `benchmark-${i}` });\n    traceTimings.push(performance.now() - start);\n  }\n\n  \u002F\u002F Measure generation creation\n  const genTimings: number[] = [];\n  const trace = langfuse.trace({ name: \"gen-benchmark\" });\n  for (let i = 0; i \u003C iterations; i++) {\n    const start = performance.now();\n    const gen = trace.generation({\n      name: `gen-${i}`,\n      model: \"gpt-4\",\n      input: [{ role: \"user\", content: \"test\" }],\n    });\n    gen.end({ output: \"response\" });\n    genTimings.push(performance.now() - start);\n  }\n\n  \u002F\u002F Measure flush\n  const flushStart = performance.now();\n  await langfuse.flushAsync();\n  const flushTime = performance.now() - flushStart;\n\n  \u002F\u002F Calculate stats\n  const stats = (arr: number[]) => ({\n    mean: arr.reduce((a, b) => a + b) \u002F arr.length,\n    p50: arr.sort((a, b) => a - b)[Math.floor(arr.length * 0.5)],\n    p95: arr.sort((a, b) => a - b)[Math.floor(arr.length * 0.95)],\n    p99: arr.sort((a, b) => a - b)[Math.floor(arr.length * 0.99)],\n  });\n\n  console.log(\"=== Langfuse Performance Benchmark ===\");\n  console.log(`\\nTrace Creation (${iterations} iterations):`);\n  console.log(JSON.stringify(stats(traceTimings), null, 2));\n  console.log(`\\nGeneration Creation (${iterations} iterations):`);\n  console.log(JSON.stringify(stats(genTimings), null, 2));\n  console.log(`\\nFlush Time: ${flushTime.toFixed(2)}ms`);\n\n  await langfuse.shutdownAsync();\n}\n\nbenchmark();\n```\n\n### Step 2: Optimize Batching Configuration\n\n```typescript\n\u002F\u002F High-throughput configuration\nconst langfuse = new Langfuse({\n  publicKey: process.env.LANGFUSE_PUBLIC_KEY!,\n  secretKey: process.env.LANGFUSE_SECRET_KEY!,\n\n  \u002F\u002F Batching optimization\n  flushAt: 100,           \u002F\u002F Larger batches = fewer requests\n  flushInterval: 10000,   \u002F\u002F Less frequent flushes  # 10000: 10 seconds in ms\n\n  \u002F\u002F Timeout tuning\n  requestTimeout: 30000,  \u002F\u002F Allow time for large batches  # 30000: 30 seconds in ms\n\n  \u002F\u002F Optional: Disable in development\n  enabled: process.env.NODE_ENV === \"production\",\n});\n```\n\n### Step 3: Implement Non-Blocking Tracing\n\n```typescript\n\u002F\u002F Trace wrapper that never blocks the main operation\nclass NonBlockingLangfuse {\n  private langfuse: Langfuse;\n  private errorCount = 0;\n  private maxErrors = 10;\n\n  constructor(config: ConstructorParameters\u003Ctypeof Langfuse>[0]) {\n    this.langfuse = new Langfuse(config);\n  }\n\n  \u002F\u002F Fire-and-forget trace\n  trace(params: Parameters\u003Ctypeof this.langfuse.trace>[0]) {\n    if (this.errorCount >= this.maxErrors) {\n      \u002F\u002F Circuit breaker: stop tracing if too many errors\n      return this.createNoOpTrace();\n    }\n\n    try {\n      return this.langfuse.trace(params);\n    } catch (error) {\n      this.errorCount++;\n      console.error(\"Langfuse trace error:\", error);\n      return this.createNoOpTrace();\n    }\n  }\n\n  private createNoOpTrace() {\n    return {\n      id: \"noop\",\n      span: () => this.createNoOpSpan(),\n      generation: () => this.createNoOpGeneration(),\n      update: () => {},\n      getTraceUrl: () => \"\",\n    };\n  }\n\n  private createNoOpSpan() {\n    return {\n      id: \"noop\",\n      span: () => this.createNoOpSpan(),\n      generation: () => this.createNoOpGeneration(),\n      end: () => {},\n    };\n  }\n\n  private createNoOpGeneration() {\n    return {\n      id: \"noop\",\n      end: () => {},\n    };\n  }\n\n  \u002F\u002F Background flush - don't await in hot path\n  flush() {\n    this.langfuse.flushAsync().catch((error) => {\n      this.errorCount++;\n      console.error(\"Langfuse flush error:\", error);\n    });\n  }\n\n  async shutdown() {\n    return this.langfuse.shutdownAsync();\n  }\n}\n```\n\n### Step 4: Optimize Data Payload Size\n\n```typescript\n\u002F\u002F Reduce trace payload size\nfunction optimizeTraceInput(input: any): any {\n  \u002F\u002F Truncate large strings\n  const MAX_STRING_LENGTH = 10000;  # 10000: 10 seconds in ms\n\n  if (typeof input === \"string\") {\n    return input.length > MAX_STRING_LENGTH\n      ? input.slice(0, MAX_STRING_LENGTH) + \"...[truncated]\"\n      : input;\n  }\n\n  if (Array.isArray(input)) {\n    \u002F\u002F Limit array size\n    const MAX_ARRAY_LENGTH = 100;\n    const truncated = input.slice(0, MAX_ARRAY_LENGTH);\n    return truncated.map(optimizeTraceInput);\n  }\n\n  if (typeof input === \"object\" && input !== null) {\n    \u002F\u002F Remove large binary data\n    const optimized: Record\u003Cstring, any> = {};\n    for (const [key, value] of Object.entries(input)) {\n      if (value instanceof Buffer || value instanceof Uint8Array) {\n        optimized[key] = `[Binary: ${value.length} bytes]`;\n      } else {\n        optimized[key] = optimizeTraceInput(value);\n      }\n    }\n    return optimized;\n  }\n\n  return input;\n}\n\n\u002F\u002F Use in traces\nconst trace = langfuse.trace({\n  name: \"optimized-trace\",\n  input: optimizeTraceInput(largeInput),\n});\n```\n\n### Step 5: Implement Sampling for Ultra-High Volume\n\n```typescript\ninterface SamplingStrategy {\n  shouldSample(params: TraceParams): boolean;\n}\n\n\u002F\u002F Deterministic sampling based on trace attributes\nclass DeterministicSampler implements SamplingStrategy {\n  private rate: number;\n\n  constructor(rate: number) {\n    this.rate = rate;\n  }\n\n  shouldSample(params: TraceParams): boolean {\n    \u002F\u002F Always sample errors\n    if (params.level === \"ERROR\" || params.tags?.includes(\"error\")) {\n      return true;\n    }\n\n    \u002F\u002F Deterministic hash-based sampling\n    const hash = this.hashString(params.name + (params.userId || \"\"));\n    return (hash % 100) \u003C (this.rate * 100);\n  }\n\n  private hashString(str: string): number {\n    let hash = 0;\n    for (let i = 0; i \u003C str.length; i++) {\n      const char = str.charCodeAt(i);\n      hash = ((hash \u003C\u003C 5) - hash) + char;\n      hash = hash & hash;\n    }\n    return Math.abs(hash);\n  }\n}\n\n\u002F\u002F Adaptive sampling based on throughput\nclass AdaptiveSampler implements SamplingStrategy {\n  private windowMs = 60000;  # 60000: 1 minute in ms\n  private maxPerWindow = 1000;  # 1000: 1 second in ms\n  private counts: number[] = [];\n\n  shouldSample(params: TraceParams): boolean {\n    const now = Date.now();\n    const windowStart = now - this.windowMs;\n\n    \u002F\u002F Clean old counts\n    this.counts = this.counts.filter((t) => t > windowStart);\n\n    \u002F\u002F Check if under limit\n    if (this.counts.length \u003C this.maxPerWindow) {\n      this.counts.push(now);\n      return true;\n    }\n\n    \u002F\u002F Over limit - only sample important traces\n    return params.level === \"ERROR\";\n  }\n}\n\n\u002F\u002F Apply sampling\nconst sampler = new DeterministicSampler(0.1); \u002F\u002F 10% sampling\n\nfunction sampledTrace(params: TraceParams) {\n  if (!sampler.shouldSample(params)) {\n    return createNoOpTrace();\n  }\n\n  return langfuse.trace({\n    ...params,\n    metadata: {\n      ...params.metadata,\n      sampled: true,\n    },\n  });\n}\n```\n\n### Step 6: Memory Management\n\n```typescript\n\u002F\u002F Prevent memory leaks with trace cleanup\nclass ManagedLangfuse {\n  private langfuse: Langfuse;\n  private activeTraces: Map\u003Cstring, { createdAt: Date }> = new Map();\n  private maxTraceAge = 300000; \u002F\u002F 5 minutes  # 300000 = configured value\n\n  constructor(config: ConstructorParameters\u003Ctypeof Langfuse>[0]) {\n    this.langfuse = new Langfuse(config);\n\n    \u002F\u002F Periodic cleanup\n    setInterval(() => this.cleanupStaleTraces(), 60000);  # 60000: 1 minute in ms\n  }\n\n  trace(params: Parameters\u003Ctypeof this.langfuse.trace>[0]) {\n    const trace = this.langfuse.trace(params);\n    this.activeTraces.set(trace.id, { createdAt: new Date() });\n    return trace;\n  }\n\n  private cleanupStaleTraces() {\n    const now = Date.now();\n    let cleaned = 0;\n\n    for (const [id, meta] of this.activeTraces) {\n      if (now - meta.createdAt.getTime() > this.maxTraceAge) {\n        this.activeTraces.delete(id);\n        cleaned++;\n      }\n    }\n\n    if (cleaned > 0) {\n      console.log(`Cleaned up ${cleaned} stale trace references`);\n    }\n  }\n\n  getStats() {\n    return {\n      activeTraces: this.activeTraces.size,\n      heapUsed: process.memoryUsage().heapUsed \u002F 1024 \u002F 1024,  # 1024: 1 KB\n    };\n  }\n}\n```\n\n## Output\n- Baseline performance measurements\n- Optimized batching configuration\n- Non-blocking trace wrapper\n- Payload size optimization\n- Sampling strategies for high volume\n- Memory leak prevention\n\n## Performance Optimization Checklist\n\n| Optimization | Impact | Effort |\n|--------------|--------|--------|\n| Increase `flushAt` | High | Low |\n| Non-blocking traces | High | Medium |\n| Payload truncation | Medium | Low |\n| Sampling | High | Medium |\n| Memory management | Medium | Medium |\n\n## Error Handling\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| High latency | Small batch size | Increase `flushAt` |\n| Memory growth | No cleanup | Add trace cleanup |\n| Request timeouts | Large payloads | Truncate inputs |\n| High CPU | Sync operations | Use async patterns |\n\n## Resources\n- [Langfuse SDK Configuration](https:\u002F\u002Flangfuse.com\u002Fdocs\u002Fsdk)\n- [Node.js Performance](https:\u002F\u002Fnodejs.org\u002Fen\u002Fdocs\u002Fguides\u002Fdont-block-the-event-loop)\n- [Sampling Strategies](https:\u002F\u002Fopentelemetry.io\u002Fdocs\u002Fconcepts\u002Fsampling\u002F)\n\n## Next Steps\nFor cost optimization, see `langfuse-cost-tuning`.\n\n## Examples\n\n**Basic usage**: Apply langfuse performance tuning to a standard project setup with default configuration options.\n\n**Advanced scenario**: Customize langfuse performance tuning for production environments with multiple constraints and team-specific requirements.",{"name":5,"author":24,"license":15,"version":25,"description":26,"allowed-tools":27,"compatible-with":28},"Jeremy Longshore \u003Cjeremy@intentsolutions.io>","1.0.0","Optimize Langfuse tracing performance for high-throughput applications.\nUse when experiencing latency issues, optimizing trace overhead,\nor scaling Langfuse for production workloads.\nTrigger with phrases like \"langfuse performance\", \"optimize langfuse\",\n\"langfuse latency\", \"langfuse overhead\", \"langfuse slow\".\n","Read, Write, Edit","claude-code, codex, openclaw","main","c2b1fdccc779e99ac814e55fb69ca8d71215dd0f","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection","https:\u002F\u002Fgithub.com\u002FSamuelChien","http:\u002F\u002Fsamuelchien.com\u002F","2026-05-26 08:27:14",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add SamuelChien\u002Fmega-skills-collection --skill langfuse-performance-tuning",{"tool":41,"command":42},"bunx","bunx skills add SamuelChien\u002Fmega-skills-collection --skill langfuse-performance-tuning",{"tool":44,"command":45},"pnpm","pnpm dlx skills add SamuelChien\u002Fmega-skills-collection --skill langfuse-performance-tuning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Flangfuse-performance-tuning\u002FSKILL.md",true,[],[50,57,64,71,78,86],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M76R4WZQZAXGGXMQCA0FZ716","zustand-store-ts","Create Zustand stores with TypeScript, subscribeWithSelector middleware, and proper state\u002Faction separation. Use when building React state management, creating global stores, or implementing reactive state patterns with Zustand.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M76R4T9KENDH7FENGZQHBW4G","zustand-store-creator","Zustand Store Creator - Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M76R3YWN84B7SANJ52X799ZE","zero-trust-config-helper","Zero Trust Config Helper - Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M76R3HNSV2AEYSKHM915GJ58","zapier-integration-helper","Zapier Integration Helper - Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M76R3DJSKAT4FA7DV4BF3GCE","zai-cli","Execute z.AI CLI providing vision, search, reader, and GitHub exploration via CLI and MCP.\nUse when user needs image\u002Fvideo analysis, OCR, UI-to-code conversion, error diagnosis,\nreal-time web search, web page to markdown extraction, or GitHub code exploration.\nTrigger with phrases like \"analyze this image\", \"search the web for\", \"read this page\",\n\"explore this repo\", or \"use zai\". Requires Z_AI_API_KEY.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzai-cli\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M76R2KAM699XE9AJVAWE4H2E","yt-research","Research competitor YouTube channels, niches, and trending topics for your content strategy.\nUse this skill whenever the user says \"research channels\", \"analyze competitors\", \"find trending topics\",\n\"niche analysis\", \"competitive research\", \"what are other creators doing\", \"scrape YouTube channels\",\nor wants to understand the competitive landscape for a specific tool or topic area. Use when working with yt research. Trigger with 'yt', 'research'.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fyt-research\u002FSKILL.md",[],[]]