Skip to content
speak-rate-limits logo

Speak Rate Limits

speak-rate-limits

Implement Speak rate limiting, backoff, and idempotency patterns for language learning APIs. Use when handling rate limit errors, implementing retry logic, or optimizing API request throughput for Speak integrations. Trigger with phrases like "speak rate limit", "speak throttling", "speak 429", "...

SKILL.md

Full skill instructions

Speak Rate Limits

Overview

Handle Speak rate limits gracefully with exponential backoff and session management for language learning applications.

Prerequisites

  • Speak SDK installed
  • Understanding of async/​await patterns
  • Access to rate limit headers

Instructions

Step 1: Understand Rate Limit Tiers

TierSessions/​hourAPI Calls/​minAudio Processing/​minBurst
Free1060205
Premium10030010025
Education500100030050
EnterpriseUnlimitedCustomCustomCustom

Step 2: Implement Exponential Backoff with Jitter

interface BackoffConfig {
  maxRetries: number;
  baseDelayMs: number;
  maxDelayMs: number;
  jitterMs: number;
}

async function withExponentialBackoff<T>(
  operation: () => Promise<T>,
  config: BackoffConfig = {
    maxRetries: 5,
    baseDelayMs: 1000,
    maxDelayMs: 32000,
    jitterMs: 500,
  }
): Promise<T> {
  for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
    try {
      return await operation();
    } catch (error: any) {
      if (attempt === config.maxRetries) throw error;

      const status = error.status || error.response?.status;
      const isRetryable = status === 429 || (status >= 500 && status < 600);

      if (!isRetryable) throw error;

      // Check for Retry-After header
      const retryAfter = error.headers?.['retry-after'];
      let delay: number;

      if (retryAfter) {
        delay = parseInt(retryAfter) * 1000;
      } else {
        // Exponential backoff with jitter
        const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);
        const jitter = Math.random() * config.jitterMs;
        delay = Math.min(exponentialDelay + jitter, config.maxDelayMs);
      }

      console.log(`Rate limited. Retrying in ${delay.toFixed(0)}ms...`);
      await new Promise(r => setTimeout(r, delay));
    }
  }
  throw new Error('Unreachable');
}

Step 3: Session-Aware Rate Limiting

// Speak uses session-based rate limits for lesson interactions
class SessionRateLimiter {
  private sessionCounts: Map<string, { count: number; windowStart: Date }> = new Map();
  private readonly maxSessionsPerHour: number;
  private readonly maxResponsesPerSession: number;

  constructor(tier: 'free' | 'premium' | 'education' = 'premium') {
    const limits = {
      free: { sessions: 10, responses: 50 },
      premium: { sessions: 100, responses: 200 },
      education: { sessions: 500, responses: 500 },
    };
    this.maxSessionsPerHour = limits[tier].sessions;
    this.maxResponsesPerSession = limits[tier].responses;
  }

  canStartSession(userId: string): boolean {
    const now = new Date();
    const windowMs = 60 * 60 * 1000; // 1 hour

    const userLimits = this.sessionCounts.get(userId);
    if (!userLimits) return true;

    // Check if window has reset
    if (now.getTime() - userLimits.windowStart.getTime() > windowMs) {
      this.sessionCounts.set(userId, { count: 0, windowStart: now });
      return true;
    }

    return userLimits.count < this.maxSessionsPerHour;
  }

  recordSessionStart(userId: string): void {
    const now = new Date();
    const current = this.sessionCounts.get(userId);

    if (!current || now.getTime() - current.windowStart.getTime() > 60 * 60 * 1000) {
      this.sessionCounts.set(userId, { count: 1, windowStart: now });
    } else {
      current.count++;
    }
  }

  getRemainingSession(userId: string): number {
    const current = this.sessionCounts.get(userId);
    if (!current) return this.maxSessionsPerHour;
    return Math.max(0, this.maxSessionsPerHour - current.count);
  }
}

Step 4: Audio Processing Queue

import PQueue from 'p-queue';

// Audio processing has stricter limits
const audioQueue = new PQueue({
  concurrency: 2, // Max 2 concurrent audio requests
  interval: 1000, // Per second
  intervalCap: 3, // Max 3 per second
});

async function queuedAudioProcessing(
  client: SpeakClient,
  audioData: ArrayBuffer,
  options: AudioProcessingOptions
): Promise<PronunciationResult> {
  return audioQueue.add(async () => {
    return client.speech.analyze(audioData, options);
  });
}

// Monitor queue status
audioQueue.on('idle', () => {
  console.log('Audio queue idle');
});

audioQueue.on('add', () => {
  console.log(`Audio queue size: ${audioQueue.size}, pending: ${audioQueue.pending}`);
});

Step 5: Rate Limit Monitor

class SpeakRateLimitMonitor {
  private apiRemaining: number = 60;
  private audioRemaining: number = 20;
  private apiResetAt: Date = new Date();
  private audioResetAt: Date = new Date();

  updateFromHeaders(headers: Headers): void {
    // API limits
    if (headers.has('X-RateLimit-Remaining')) {
      this.apiRemaining = parseInt(headers.get('X-RateLimit-Remaining')!);
    }
    if (headers.has('X-RateLimit-Reset')) {
      this.apiResetAt = new Date(parseInt(headers.get('X-RateLimit-Reset')!) * 1000);
    }

    // Audio-specific limits
    if (headers.has('X-Audio-RateLimit-Remaining')) {
      this.audioRemaining = parseInt(headers.get('X-Audio-RateLimit-Remaining')!);
    }
    if (headers.has('X-Audio-RateLimit-Reset')) {
      this.audioResetAt = new Date(parseInt(headers.get('X-Audio-RateLimit-Reset')!) * 1000);
    }
  }

  shouldThrottleApi(): boolean {
    return this.apiRemaining < 5 && new Date() < this.apiResetAt;
  }

  shouldThrottleAudio(): boolean {
    return this.audioRemaining < 3 && new Date() < this.audioResetAt;
  }

  getApiWaitTime(): number {
    return Math.max(0, this.apiResetAt.getTime() - Date.now());
  }

  getAudioWaitTime(): number {
    return Math.max(0, this.audioResetAt.getTime() - Date.now());
  }

  getStatus(): RateLimitStatus {
    return {
      api: {
        remaining: this.apiRemaining,
        resetAt: this.apiResetAt,
        throttled: this.shouldThrottleApi(),
      },
      audio: {
        remaining: this.audioRemaining,
        resetAt: this.audioResetAt,
        throttled: this.shouldThrottleAudio(),
      },
    };
  }
}

Step 6: Idempotency for Lesson Responses

import crypto from 'crypto';

// Generate deterministic key for lesson responses
function generateIdempotencyKey(
  sessionId: string,
  responseText: string,
  timestamp: number
): string {
  const data = JSON.stringify({ sessionId, responseText, timestamp });
  return crypto.createHash('sha256').update(data).digest('hex').slice(0, 32);
}

async function idempotentSubmitResponse(
  session: LessonSession,
  response: LessonResponse,
  idempotencyKey?: string
): Promise<TutorFeedback> {
  const key = idempotencyKey || generateIdempotencyKey(
    session.id,
    response.text,
    Math.floor(Date.now() / 10000) // 10-second buckets
  );

  return session.submitResponse(response, {
    headers: { 'Idempotency-Key': key },
  });
}

Output

  • Reliable API calls with automatic retry
  • Session-aware rate limiting
  • Audio processing queue
  • Rate limit monitoring
  • Idempotent lesson responses

Error Handling

HeaderDescriptionAction
X-RateLimit-LimitMax requestsMonitor usage
X-RateLimit-RemainingRemaining requestsThrottle if low
X-RateLimit-ResetReset timestampWait until reset
X-Audio-RateLimit-RemainingAudio requests leftQueue audio processing
Retry-AfterSeconds to waitHonor this value

Examples

Pre-flight Rate Check

async function safeSpeakCall<T>(
  monitor: SpeakRateLimitMonitor,
  operation: () => Promise<T>,
  isAudioOperation: boolean = false
): Promise<T> {
  // Check if we should wait
  if (isAudioOperation && monitor.shouldThrottleAudio()) {
    const waitTime = monitor.getAudioWaitTime();
    console.log(`Audio rate limit - waiting ${waitTime}ms`);
    await new Promise(r => setTimeout(r, waitTime));
  } else if (monitor.shouldThrottleApi()) {
    const waitTime = monitor.getApiWaitTime();
    console.log(`API rate limit - waiting ${waitTime}ms`);
    await new Promise(r => setTimeout(r, waitTime));
  }

  return withExponentialBackoff(operation);
}

Batch Lesson Processing

async function batchProcessLessons(
  client: SpeakClient,
  lessons: LessonConfig[],
  rateLimiter: SessionRateLimiter
): Promise<LessonResult[]> {
  const results: LessonResult[] = [];

  for (const lesson of lessons) {
    // Check rate limit before starting
    if (!rateLimiter.canStartSession(lesson.userId)) {
      console.log(`Rate limited for user ${lesson.userId}, skipping`);
      results.push({ success: false, error: 'RATE_LIMITED' });
      continue;
    }

    rateLimiter.recordSessionStart(lesson.userId);

    try {
      const result = await withExponentialBackoff(() =>
        client.tutor.runLesson(lesson)
      );
      results.push({ success: true, data: result });
    } catch (error) {
      results.push({ success: false, error });
    }

    // Small delay between lessons
    await new Promise(r => setTimeout(r, 100));
  }

  return results;
}

Resources

Next Steps

For security configuration, see speak-security-basics.

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