Skip to content
deepgram-performance-tuning logo

Deepgram Performance Tuning

deepgram-performance-tuning

Optimize Deepgram API performance for faster transcription and lower latency. Use when improving transcription speed, reducing latency, or optimizing audio processing pipelines. Trigger with phrases like "deepgram performance", "speed up deepgram", "optimize transcription", "deepgram latency", "d...

SKILL.md

Full skill instructions

Deepgram Performance Tuning

Overview

Optimize Deepgram integration performance through audio preprocessing, connection management, and configuration tuning.

Prerequisites

  • Working Deepgram integration
  • Performance monitoring in place
  • Audio processing capabilities
  • Baseline metrics established

Performance Factors

FactorImpactOptimization
Audio FormatHighUse optimal encoding
Sample RateMediumMatch model requirements
File SizeHighStream large files
Model ChoiceHighBalance accuracy vs speed
Network LatencyMediumUse closest region
ConcurrencyMediumManage connections

Instructions

Step 1: Optimize Audio Format

Preprocess audio for optimal transcription.

Step 2: Configure Connection Pooling

Reuse connections for better throughput.

Step 3: Tune API Parameters

Select appropriate model and features.

Step 4: Implement Streaming

Use streaming for real-time and large files.

Examples

Audio Preprocessing

// lib/​audio-optimizer.ts
import ffmpeg from 'fluent-ffmpeg';
import { Readable } from 'stream';

interface OptimizedAudio {
  buffer: Buffer;
  mimetype: string;
  sampleRate: number;
  channels: number;
  duration: number;
}

export async function optimizeAudio(inputPath: string): Promise<OptimizedAudio> {
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];

    // Optimal settings for Deepgram
    ffmpeg(inputPath)
      .audioCodec('pcm_s16le')      // 16-bit PCM
      .audioChannels(1)              // Mono
      .audioFrequency(16000)         // 16kHz (optimal for speech)
      .format('wav')
      .on('error', reject)
      .on('end', () => {
        const buffer = Buffer.concat(chunks);
        resolve({
          buffer,
          mimetype: 'audio/​wav',
          sampleRate: 16000,
          channels: 1,
          duration: buffer.length / (16000 * 2), // 16-bit = 2 bytes
        });
      })
      .pipe()
      .on('data', (chunk: Buffer) => chunks.push(chunk));
  });
}

// For already loaded audio data
export async function optimizeAudioBuffer(
  audioBuffer: Buffer,
  inputFormat: string
): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    const readable = new Readable();
    readable.push(audioBuffer);
    readable.push(null);

    ffmpeg(readable)
      .inputFormat(inputFormat)
      .audioCodec('pcm_s16le')
      .audioChannels(1)
      .audioFrequency(16000)
      .format('wav')
      .on('error', reject)
      .on('end', () => resolve(Buffer.concat(chunks)))
      .pipe()
      .on('data', (chunk: Buffer) => chunks.push(chunk));
  });
}

Connection Pooling

// lib/​connection-pool.ts
import { createClient, DeepgramClient } from '@deepgram/​sdk';

interface PoolConfig {
  minSize: number;
  maxSize: number;
  acquireTimeout: number;
  idleTimeout: number;
}

class DeepgramConnectionPool {
  private pool: DeepgramClient[] = [];
  private inUse: Set<DeepgramClient> = new Set();
  private waiting: Array<(client: DeepgramClient) => void> = [];
  private config: PoolConfig;
  private apiKey: string;

  constructor(apiKey: string, config: Partial<PoolConfig> = {}) {
    this.apiKey = apiKey;
    this.config = {
      minSize: config.minSize ?? 2,
      maxSize: config.maxSize ?? 10,
      acquireTimeout: config.acquireTimeout ?? 10000,
      idleTimeout: config.idleTimeout ?? 60000,
    };

    // Initialize minimum connections
    for (let i = 0; i < this.config.minSize; i++) {
      this.pool.push(createClient(this.apiKey));
    }
  }

  async acquire(): Promise<DeepgramClient> {
    // Try to get from pool
    if (this.pool.length > 0) {
      const client = this.pool.pop()!;
      this.inUse.add(client);
      return client;
    }

    // Create new if under max
    if (this.inUse.size < this.config.maxSize) {
      const client = createClient(this.apiKey);
      this.inUse.add(client);
      return client;
    }

    // Wait for available connection
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        const index = this.waiting.indexOf(resolve);
        if (index > -1) this.waiting.splice(index, 1);
        reject(new Error('Connection acquire timeout'));
      }, this.config.acquireTimeout);

      this.waiting.push((client) => {
        clearTimeout(timeout);
        resolve(client);
      });
    });
  }

  release(client: DeepgramClient): void {
    this.inUse.delete(client);

    if (this.waiting.length > 0) {
      const waiter = this.waiting.shift()!;
      this.inUse.add(client);
      waiter(client);
    } else {
      this.pool.push(client);
    }
  }

  async execute<T>(fn: (client: DeepgramClient) => Promise<T>): Promise<T> {
    const client = await this.acquire();
    try {
      return await fn(client);
    } finally {
      this.release(client);
    }
  }

  getStats() {
    return {
      poolSize: this.pool.length,
      inUse: this.inUse.size,
      waiting: this.waiting.length,
    };
  }
}

export const pool = new DeepgramConnectionPool(process.env.DEEPGRAM_API_KEY!);

Streaming for Large Files

// lib/​streaming-transcription.ts
import { createClient } from '@deepgram/​sdk';
import { createReadStream, statSync } from 'fs';

interface StreamingOptions {
  chunkSize: number;
  model: string;
}

export async function streamLargeFile(
  filePath: string,
  options: Partial<StreamingOptions> = {}
): Promise<string> {
  const { chunkSize = 1024 * 1024, model = 'nova-2' } = options;
  const client = createClient(process.env.DEEPGRAM_API_KEY!);

  const fileSize = statSync(filePath).size;
  const transcripts: string[] = [];

  // Use live transcription for streaming
  const connection = client.listen.live({
    model,
    smart_format: true,
    punctuate: true,
  });

  return new Promise((resolve, reject) => {
    connection.on('open', () => {
      const stream = createReadStream(filePath, { highWaterMark: chunkSize });

      stream.on('data', (chunk: Buffer) => {
        connection.send(chunk);
      });

      stream.on('end', () => {
        connection.finish();
      });

      stream.on('error', reject);
    });

    connection.on('transcript', (data) => {
      if (data.is_final) {
        transcripts.push(data.channel.alternatives[0].transcript);
      }
    });

    connection.on('close', () => {
      resolve(transcripts.join(' '));
    });

    connection.on('error', reject);
  });
}

Model Selection for Speed

// lib/​model-selector.ts
interface ModelConfig {
  name: string;
  accuracy: 'high' | 'medium' | 'low';
  speed: 'fast' | 'medium' | 'slow';
  costPerMinute: number;
}

const models: Record<string, ModelConfig> = {
  'nova-2': {
    name: 'Nova-2',
    accuracy: 'high',
    speed: 'fast',
    costPerMinute: 0.0043,
  },
  'nova': {
    name: 'Nova',
    accuracy: 'high',
    speed: 'fast',
    costPerMinute: 0.0043,
  },
  'enhanced': {
    name: 'Enhanced',
    accuracy: 'medium',
    speed: 'fast',
    costPerMinute: 0.0145,
  },
  'base': {
    name: 'Base',
    accuracy: 'low',
    speed: 'fast',
    costPerMinute: 0.0048,
  },
};

export function selectModel(requirements: {
  prioritize: 'accuracy' | 'speed' | 'cost';
  minAccuracy?: 'high' | 'medium' | 'low';
}): string {
  const { prioritize, minAccuracy = 'low' } = requirements;

  const accuracyOrder = ['high', 'medium', 'low'];
  const minAccuracyIndex = accuracyOrder.indexOf(minAccuracy);

  const eligible = Object.entries(models).filter(([_, config]) =>
    accuracyOrder.indexOf(config.accuracy) <= minAccuracyIndex
  );

  if (prioritize === 'accuracy') {
    return eligible.reduce((best, [name, config]) =>
      accuracyOrder.indexOf(config.accuracy) < accuracyOrder.indexOf(models[best].accuracy)
        ? name : best
    , eligible[0][0]);
  }

  if (prioritize === 'cost') {
    return eligible.reduce((best, [name, config]) =>
      config.costPerMinute < models[best].costPerMinute ? name : best
    , eligible[0][0]);
  }

  // Default: balance speed and accuracy
  return 'nova-2';
}

Parallel Processing

// lib/​parallel-transcription.ts
import { pool } from './​connection-pool';
import pLimit from 'p-limit';

interface TranscriptionResult {
  file: string;
  transcript: string;
  duration: number;
}

export async function transcribeMultiple(
  audioUrls: string[],
  concurrency = 5
): Promise<TranscriptionResult[]> {
  const limit = pLimit(concurrency);
  const startTime = Date.now();

  const results = await Promise.all(
    audioUrls.map((url, index) =>
      limit(async () => {
        const itemStart = Date.now();

        const result = await pool.execute(async (client) => {
          const { result, error } = await client.listen.prerecorded.transcribeUrl(
            { url },
            { model: 'nova-2', smart_format: true }
          );

          if (error) throw error;
          return result;
        });

        return {
          file: url,
          transcript: result.results.channels[0].alternatives[0].transcript,
          duration: Date.now() - itemStart,
        };
      })
    )
  );

  console.log(`Processed ${audioUrls.length} files in ${Date.now() - startTime}ms`);
  console.log(`Average per file: ${(Date.now() - startTime) / audioUrls.length}ms`);

  return results;
}

Caching Results

// lib/​transcription-cache.ts
import { createHash } from 'crypto';
import { redis } from './​redis';

interface CacheOptions {
  ttl: number; // seconds
}

export class TranscriptionCache {
  private ttl: number;

  constructor(options: Partial<CacheOptions> = {}) {
    this.ttl = options.ttl ?? 3600; // 1 hour default
  }

  private getCacheKey(audioUrl: string, options: Record<string, unknown>): string {
    const hash = createHash('sha256')
      .update(JSON.stringify({ audioUrl, options }))
      .digest('hex');
    return `transcription:${hash}`;
  }

  async get(
    audioUrl: string,
    options: Record<string, unknown>
  ): Promise<string | null> {
    const key = this.getCacheKey(audioUrl, options);
    return redis.get(key);
  }

  async set(
    audioUrl: string,
    options: Record<string, unknown>,
    transcript: string
  ): Promise<void> {
    const key = this.getCacheKey(audioUrl, options);
    await redis.setex(key, this.ttl, transcript);
  }

  async transcribeWithCache(
    transcribeFn: () => Promise<string>,
    audioUrl: string,
    options: Record<string, unknown>
  ): Promise<{ transcript: string; cached: boolean }> {
    const cached = await this.get(audioUrl, options);
    if (cached) {
      return { transcript: cached, cached: true };
    }

    const transcript = await transcribeFn();
    await this.set(audioUrl, options, transcript);

    return { transcript, cached: false };
  }
}

Performance Metrics

// lib/​performance-metrics.ts
import { Histogram, Counter, Gauge } from 'prom-client';

export const transcriptionLatency = new Histogram({
  name: 'deepgram_transcription_latency_seconds',
  help: 'Latency of transcription requests',
  labelNames: ['model', 'status'],
  buckets: [0.5, 1, 2, 5, 10, 30, 60],
});

export const audioDuration = new Histogram({
  name: 'deepgram_audio_duration_seconds',
  help: 'Duration of audio files processed',
  buckets: [10, 30, 60, 120, 300, 600, 1800],
});

export const processingRatio = new Gauge({
  name: 'deepgram_processing_ratio',
  help: 'Ratio of processing time to audio duration',
  labelNames: ['model'],
});

export function measureTranscription(
  audioDurationSec: number,
  processingTimeSec: number,
  model: string
) {
  audioDuration.observe(audioDurationSec);
  processingRatio.labels(model).set(processingTimeSec / audioDurationSec);
}

Resources

Next Steps

Proceed to deepgram-cost-tuning for cost optimization.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View