deepgram-rate-limits

0
0
Source

Implement Deepgram rate limiting and backoff strategies. Use when handling API quotas, implementing request throttling, or dealing with rate limit errors. Trigger with phrases like "deepgram rate limit", "deepgram throttling", "429 error deepgram", "deepgram quota", "deepgram backoff".

Install

mkdir -p .claude/skills/deepgram-rate-limits && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8574" && unzip -o skill.zip -d .claude/skills/deepgram-rate-limits && rm skill.zip

Installs to .claude/skills/deepgram-rate-limits

About this skill

Deepgram Rate Limits

Overview

Implement rate limiting, exponential backoff, and circuit breaker patterns for Deepgram API. Deepgram limits by concurrent connections (not requests per second). Understanding this model is key to building reliable integrations.

Deepgram Rate Limit Model

Deepgram uses concurrency-based limits, not traditional requests-per-minute:

PlanConcurrent Requests (STT)Concurrent Connections (Live)Concurrent Requests (TTS)
Pay As You Go100100100
Growth200200200
EnterpriseCustomCustomCustom

When you exceed your concurrency limit, Deepgram returns 429 Too Many Requests.

Key insight: You can send unlimited total requests — just not more than your concurrency limit simultaneously.

Instructions

Step 1: Concurrency-Aware Queue

import pLimit from 'p-limit';
import { createClient } from '@deepgram/sdk';

class DeepgramRateLimiter {
  private limit: ReturnType<typeof pLimit>;
  private client: ReturnType<typeof createClient>;
  private stats = { total: 0, active: 0, queued: 0, errors: 0 };

  constructor(apiKey: string, maxConcurrent = 50) {
    // Stay well under plan limit (e.g., 50 of 100 allowed)
    this.limit = pLimit(maxConcurrent);
    this.client = createClient(apiKey);
  }

  async transcribe(source: { url: string }, options: Record<string, any>) {
    this.stats.queued++;
    return this.limit(async () => {
      this.stats.queued--;
      this.stats.active++;
      this.stats.total++;
      try {
        const { result, error } = await this.client.listen.prerecorded.transcribeUrl(
          source, options
        );
        if (error) {
          this.stats.errors++;
          throw error;
        }
        return result;
      } catch (err) {
        this.stats.errors++;
        throw err;
      } finally {
        this.stats.active--;
      }
    });
  }

  getStats() { return { ...this.stats }; }
}

// Usage:
const limiter = new DeepgramRateLimiter(process.env.DEEPGRAM_API_KEY!, 50);
const urls = ['audio1.wav', 'audio2.wav', /* ...hundreds more */];
const results = await Promise.allSettled(
  urls.map(url => limiter.transcribe({ url }, { model: 'nova-3', smart_format: true }))
);

Step 2: Exponential Backoff with Jitter

class RetryableDeepgramClient {
  private client: ReturnType<typeof createClient>;

  constructor(apiKey: string) {
    this.client = createClient(apiKey);
  }

  async transcribeWithRetry(
    source: any,
    options: any,
    config = { maxRetries: 5, baseDelay: 1000, maxDelay: 60000 }
  ) {
    let lastError: Error | null = null;

    for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
      try {
        const { result, error } = await this.client.listen.prerecorded.transcribeUrl(
          source, options
        );
        if (!error) return result;

        // Non-retryable errors (4xx except 429, 408)
        const status = (error as any).status;
        if (status >= 400 && status < 500 && status !== 429 && status !== 408) {
          throw new Error(`Non-retryable error ${status}: ${error.message}`);
        }
        lastError = error;
      } catch (err: any) {
        if (err.message.startsWith('Non-retryable')) throw err;
        lastError = err;
      }

      if (attempt < config.maxRetries) {
        // Exponential backoff: 1s, 2s, 4s, 8s, 16s + random jitter
        const delay = Math.min(
          config.baseDelay * Math.pow(2, attempt) + Math.random() * 1000,
          config.maxDelay
        );
        console.log(`Retry ${attempt + 1}/${config.maxRetries} in ${Math.round(delay)}ms`);
        await new Promise(r => setTimeout(r, delay));
      }
    }
    throw lastError ?? new Error('Max retries exceeded');
  }
}

Step 3: Circuit Breaker

enum CircuitState { CLOSED, OPEN, HALF_OPEN }

class DeepgramCircuitBreaker {
  private state = CircuitState.CLOSED;
  private failureCount = 0;
  private lastFailureTime = 0;
  private successCount = 0;

  constructor(
    private failureThreshold = 5,
    private resetTimeout = 30000,     // 30 seconds
    private halfOpenMaxRequests = 3,
  ) {}

  async execute<T>(fn: () => Promise<T>): Promise<T> {
    if (this.state === CircuitState.OPEN) {
      if (Date.now() - this.lastFailureTime >= this.resetTimeout) {
        this.state = CircuitState.HALF_OPEN;
        this.successCount = 0;
      } else {
        throw new Error(`Circuit OPEN — retry in ${
          Math.ceil((this.resetTimeout - (Date.now() - this.lastFailureTime)) / 1000)
        }s`);
      }
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      throw err;
    }
  }

  private onSuccess() {
    if (this.state === CircuitState.HALF_OPEN) {
      this.successCount++;
      if (this.successCount >= this.halfOpenMaxRequests) {
        this.state = CircuitState.CLOSED;
        this.failureCount = 0;
      }
    } else {
      this.failureCount = 0;
    }
  }

  private onFailure() {
    this.failureCount++;
    this.lastFailureTime = Date.now();
    if (this.failureCount >= this.failureThreshold) {
      this.state = CircuitState.OPEN;
      console.error(`Circuit OPEN after ${this.failureCount} failures`);
    }
  }

  getState() { return CircuitState[this.state]; }
}

Step 4: Combined Rate Limiter + Circuit Breaker

class ResilientDeepgramClient {
  private limiter: DeepgramRateLimiter;
  private breaker: DeepgramCircuitBreaker;
  private retryClient: RetryableDeepgramClient;

  constructor(apiKey: string, maxConcurrent = 50) {
    this.limiter = new DeepgramRateLimiter(apiKey, maxConcurrent);
    this.breaker = new DeepgramCircuitBreaker();
    this.retryClient = new RetryableDeepgramClient(apiKey);
  }

  async transcribe(audioUrl: string, options: Record<string, any> = {}) {
    return this.breaker.execute(() =>
      this.retryClient.transcribeWithRetry(
        { url: audioUrl },
        { model: 'nova-3', smart_format: true, ...options }
      )
    );
  }
}

// Production usage
const client = new ResilientDeepgramClient(process.env.DEEPGRAM_API_KEY!, 50);
const result = await client.transcribe('https://example.com/audio.wav');

Step 5: Usage Monitoring

// Query Deepgram's usage API to track consumption
async function checkUsage(client: ReturnType<typeof createClient>, projectId: string) {
  const { result } = await client.manage.getUsage(projectId, {
    start: new Date(Date.now() - 86400000).toISOString(), // Last 24 hours
    end: new Date().toISOString(),
  });

  const totalMinutes = (result as any).results?.reduce(
    (sum: number, r: any) => sum + (r.hours * 60 + r.minutes), 0
  ) ?? 0;

  console.log(`Last 24h usage: ${totalMinutes.toFixed(1)} minutes`);
  return totalMinutes;
}

Output

  • Concurrency-aware request queue with p-limit
  • Exponential backoff with jitter for 429/5xx errors
  • Circuit breaker (CLOSED -> OPEN -> HALF_OPEN)
  • Combined resilient client pattern
  • Usage monitoring via Deepgram API

Error Handling

IssueCauseResolution
429 Too Many RequestsConcurrency limit exceededLower maxConcurrent, implement backoff
Circuit breaker OPEN5+ consecutive failuresWait for reset, check status.deepgram.com
Queue growing unboundedSustained high loadIncrease plan limits or scale horizontally
Usage API returns emptyWrong project IDVerify project ID from getProjects()

Resources

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

8227

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

4926

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

14217

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4615

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

11514

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

11410

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,1421,171

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

969933

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

683829

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

691549

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

797540

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

697374

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.