TW

twinmind-rate-limits

A guide to implementing exponential backoff and request optimization to manage TwinMind API rate limits.

Install

mkdir -p .claude/skills/twinmind-rate-limits && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3516" && unzip -o skill.zip -d .claude/skills/twinmind-rate-limits && rm skill.zip

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

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement TwinMind rate limiting, backoff, and optimization patterns.
69 charsno explicit “when” trigger
Advanced

Key capabilities

  • Understand TwinMind API rate limit tiers and key limits.
  • Implement exponential backoff with jitter for retrying failed requests.
  • Create a request queue to manage API concurrency and interval caps.
  • Monitor rate limit headers from TwinMind API responses.
  • Batch process requests for efficiency.
  • Throttle requests proactively based on remaining quota.

How it works

This skill provides code patterns for handling TwinMind API rate limits by implementing exponential backoff with jitter, managing requests through a queue, and monitoring rate limit headers to optimize throughput.

Inputs & outputs

You give it
API operation function, rate limit configuration, TwinMind API responses
You get back
Successful API call result, delayed retry, queued requests, rate limit status

When to use twinmind-rate-limits

  • Handle TwinMind rate limit errors
  • Implement retry logic with backoff
  • Optimize API request throughput
  • Monitor concurrency limits for transcriptions

About this skill

TwinMind Rate Limits

Overview

Handle TwinMind rate limits gracefully with exponential backoff and request optimization.

Prerequisites

  • TwinMind API access (Pro/Enterprise)
  • Understanding of async/await patterns
  • Familiarity with rate limiting concepts

Instructions

Step 1: Understand Rate Limit Tiers

TierAudio Hours/MonthAPI Requests/MinConcurrent TranscriptionsBurst
FreeUnlimited3015
Pro ($10/mo)Unlimited60315
EnterpriseUnlimited3001050

Key Limits:

  • Transcription: Based on audio duration ($0.23/hour with Ear-3)
  • AI Operations: Token-based (2M context for Pro)
  • Summarization: 10/minute (Free), 30/minute (Pro)
  • Memory Search: 60/minute (Free), 300/minute (Pro)

Step 2: Implement Exponential Backoff with Jitter

// src/twinmind/rate-limit.ts
interface RateLimitConfig {
  maxRetries: number;
  baseDelayMs: number;
  maxDelayMs: number;
  jitterMs: number;
}

const defaultConfig: RateLimitConfig = {
  maxRetries: 5,
  baseDelayMs: 1000,  # 1000: 1 second in ms
  maxDelayMs: 60000, // Max 1 minute  # 60000: 1 minute in ms
  jitterMs: 500,  # HTTP 500 Internal Server Error
};

export async function withRateLimit<T>(
  operation: () => Promise<T>,
  config: Partial<RateLimitConfig> = {}
): Promise<T> {
  const { maxRetries, baseDelayMs, maxDelayMs, jitterMs } = {
    ...defaultConfig,
    ...config,
  };

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (error: any) {
      if (attempt === maxRetries) throw error;

      const status = error.response?.status;
      if (status !== 429 && status !== 503) throw error; // Only retry on rate limits  # 503: HTTP 429 Too Many Requests

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

      if (retryAfter) {
        delay = parseInt(retryAfter) * 1000;  # 1 second in ms
      } else {
        // Exponential backoff with jitter
        const exponential = baseDelayMs * Math.pow(2, attempt);
        const jitter = Math.random() * jitterMs;
        delay = Math.min(exponential + jitter, maxDelayMs);
      }

      console.log(`Rate limited (attempt ${attempt + 1}). Waiting ${delay}ms...`);
      await new Promise(r => setTimeout(r, delay));
    }
  }

  throw new Error('Max retries exceeded');
}

Step 3: Implement Request Queue

// src/twinmind/queue.ts
import PQueue from 'p-queue';

interface QueueConfig {
  concurrency: number;
  intervalMs: number;
  intervalCap: number;
}

const tierConfigs: Record<string, QueueConfig> = {
  free: { concurrency: 1, intervalMs: 60000, intervalCap: 30 },  # 60000: 1 minute in ms
  pro: { concurrency: 3, intervalMs: 60000, intervalCap: 60 },  # 1 minute in ms
  enterprise: { concurrency: 10, intervalMs: 60000, intervalCap: 300 },  # 300: 1 minute in ms
};

export class TwinMindQueue {
  private queue: PQueue;
  private tier: string;

  constructor(tier: 'free' | 'pro' | 'enterprise' = 'pro') {
    const config = tierConfigs[tier];
    this.tier = tier;
    this.queue = new PQueue({
      concurrency: config.concurrency,
      interval: config.intervalMs,
      intervalCap: config.intervalCap,
    });
  }

  async add<T>(operation: () => Promise<T>, priority?: number): Promise<T> {
    return this.queue.add(operation, { priority }) as Promise<T>;
  }

  get pending(): number {
    return this.queue.pending;
  }

  get size(): number {
    return this.queue.size;
  }

  pause(): void {
    this.queue.pause();
  }

  resume(): void {
    this.queue.start();
  }

  clear(): void {
    this.queue.clear();
  }
}

// Singleton instance
let queueInstance: TwinMindQueue | null = null;

export function getQueue(tier?: 'free' | 'pro' | 'enterprise'): TwinMindQueue {
  if (!queueInstance) {
    queueInstance = new TwinMindQueue(tier);
  }
  return queueInstance;
}

Step 4: Monitor Rate Limit Headers

// src/twinmind/rate-monitor.ts
export interface RateLimitStatus {
  limit: number;
  remaining: number;
  reset: Date;
  percentUsed: number;
}

export class RateLimitMonitor {
  private limits = new Map<string, RateLimitStatus>();

  updateFromResponse(endpoint: string, headers: Headers): void {
    const limit = parseInt(headers.get('X-RateLimit-Limit') || '60');
    const remaining = parseInt(headers.get('X-RateLimit-Remaining') || '60');
    const resetTimestamp = headers.get('X-RateLimit-Reset');
    const reset = resetTimestamp
      ? new Date(parseInt(resetTimestamp) * 1000)  # 1000: 1 second in ms
      : new Date(Date.now() + 60000);  # 60000: 1 minute in ms

    this.limits.set(endpoint, {
      limit,
      remaining,
      reset,
      percentUsed: ((limit - remaining) / limit) * 100,
    });
  }

  getStatus(endpoint: string): RateLimitStatus | undefined {
    return this.limits.get(endpoint);
  }

  shouldThrottle(endpoint: string, threshold = 10): boolean {
    const status = this.limits.get(endpoint);
    if (!status) return false;

    // Throttle if remaining < threshold AND reset hasn't happened
    return status.remaining < threshold && new Date() < status.reset;
  }

  getWaitTime(endpoint: string): number {
    const status = this.limits.get(endpoint);
    if (!status) return 0;

    const now = Date.now();
    const resetTime = status.reset.getTime();

    return Math.max(0, resetTime - now);
  }

  getAllStatuses(): Map<string, RateLimitStatus> {
    return new Map(this.limits);
  }
}

export const rateLimitMonitor = new RateLimitMonitor();

Step 5: Implement Adaptive Rate Limiting

// src/twinmind/adaptive-limiter.ts
export class AdaptiveRateLimiter {
  private successCount = 0;
  private failureCount = 0;
  private currentDelay = 0;
  private minDelay = 0;
  private maxDelay = 5000;  # 5000: 5 seconds in ms
  private windowMs = 60000;  # 60000: 1 minute in ms
  private windowStart = Date.now();

  recordSuccess(): void {
    this.maybeResetWindow();
    this.successCount++;

    // Decrease delay on success (min 0)
    if (this.currentDelay > 0) {
      this.currentDelay = Math.max(0, this.currentDelay - 100);
    }
  }

  recordFailure(isRateLimit: boolean): void {
    this.maybeResetWindow();
    this.failureCount++;

    if (isRateLimit) {
      // Increase delay on rate limit
      this.currentDelay = Math.min(this.maxDelay, this.currentDelay + 500);  # HTTP 500 Internal Server Error
    }
  }

  private maybeResetWindow(): void {
    const now = Date.now();
    if (now - this.windowStart > this.windowMs) {
      this.successCount = 0;
      this.failureCount = 0;
      this.windowStart = now;
    }
  }

  getDelay(): number {
    return this.currentDelay;
  }

  getMetrics(): { success: number; failure: number; delay: number; ratio: number } {
    const total = this.successCount + this.failureCount;
    return {
      success: this.successCount,
      failure: this.failureCount,
      delay: this.currentDelay,
      ratio: total > 0 ? this.successCount / total : 1,
    };
  }

  async wait(): Promise<void> {
    if (this.currentDelay > 0) {
      await new Promise(r => setTimeout(r, this.currentDelay));
    }
  }
}

Step 6: Batch Requests for Efficiency

// src/twinmind/batch.ts
export interface BatchOptions {
  maxBatchSize: number;
  maxWaitMs: number;
}

export class TranscriptionBatcher {
  private pending: Array<{
    audioUrl: string;
    resolve: (value: any) => void;
    reject: (error: any) => void;
  }> = [];
  private timer: NodeJS.Timeout | null = null;
  private options: BatchOptions;

  constructor(options: Partial<BatchOptions> = {}) {
    this.options = {
      maxBatchSize: 5,
      maxWaitMs: 1000,  # 1000: 1 second in ms
      ...options,
    };
  }

  async transcribe(audioUrl: string): Promise<any> {
    return new Promise((resolve, reject) => {
      this.pending.push({ audioUrl, resolve, reject });

      if (this.pending.length >= this.options.maxBatchSize) {
        this.flush();
      } else if (!this.timer) {
        this.timer = setTimeout(() => this.flush(), this.options.maxWaitMs);
      }
    });
  }

  private async flush(): Promise<void> {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }

    const batch = this.pending.splice(0, this.options.maxBatchSize);
    if (batch.length === 0) return;

    try {
      // Use batch API if available
      const results = await this.processBatch(batch.map(b => b.audioUrl));

      batch.forEach((item, index) => {
        item.resolve(results[index]);
      });
    } catch (error) {
      batch.forEach(item => item.reject(error));
    }
  }

  private async processBatch(audioUrls: string[]): Promise<any[]> {
    const client = getTwinMindClient();
    const response = await client.post('/transcribe/batch', {
      audio_urls: audioUrls,
      model: 'ear-3',
    });
    return response.data.transcripts;
  }
}

Output

  • Reliable API calls with automatic retry
  • Request queue with rate limit awareness
  • Adaptive throttling based on response patterns
  • Batch processing for efficiency
  • Real-time rate limit monitoring

Error Handling

HeaderDescriptionAction
X-RateLimit-LimitMax requests per windowMonitor total quota
X-RateLimit-RemainingRemaining in windowThrottle when low
X-RateLimit-ResetUnix timestamp of resetWait until reset
Retry-AfterSeconds to waitHonor this value

Rate Limit Best Practices

  1. Always handle 429 responses - Never let rate limits crash your app
  2. Use request queues - Don't burst requests
  3. Monitor remaining quota - Throttle before hitting limits
  4. Implement circuit breakers - Fail fast when API is overloaded
  5. Cache responses - Avoid redundant requests
  6. **Bat

Content truncated.

When not to use it

  • When TwinMind API access is not Pro/Enterprise.
  • When not familiar with async/await patterns.

Prerequisites

TwinMind API access (Pro/Enterprise)Understanding of async/await patternsFamiliarity with rate limiting concepts

Limitations

  • Max retries can be exceeded.
  • Queue concurrency and interval caps are tier-dependent.
  • Batch processing requires a batch API if available.

How it compares

This skill offers specific code implementations for TwinMind API rate limiting, including exponential backoff and request queuing, which is more concrete than general rate limiting advice.

Compared to similar skills

twinmind-rate-limits side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
twinmind-rate-limits (this skill)126dNo flagsAdvanced
deepgram-performance-tuning326dReviewIntermediate
graphql66moNo flagsAdvanced
guidewire-sdk-patterns226dReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

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

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

deepgram-performance-tuning

jeremylongshore

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", "deepgram faster".

333

graphql

davila7

GraphQL gives clients exactly the data they need - no more, no less. One endpoint, typed schema, introspection. But the flexibility that makes it powerful also makes it dangerous. Without proper controls, clients can craft queries that bring down your server. This skill covers schema design, resolvers, DataLoader for N+1 prevention, federation for microservices, and client integration with Apollo/urql. Key insight: GraphQL is a contract. The schema is the API documentation. Design it carefully.

624

guidewire-sdk-patterns

jeremylongshore

Master Guidewire SDK patterns including Digital SDK, REST API Client, and Gosu best practices. Use when implementing integrations, building frontends with Jutro, or writing server-side Gosu code. Trigger with phrases like "guidewire sdk", "digital sdk", "jutro sdk", "guidewire patterns", "gosu best practices", "rest api client".

215

groq-performance-tuning

jeremylongshore

Optimize Groq API performance with caching, batching, and connection pooling. Use when experiencing slow API responses, implementing caching strategies, or optimizing request throughput for Groq integrations. Trigger with phrases like "groq performance", "optimize groq", "groq latency", "groq caching", "groq slow", "groq batch".

111

openrouter-streaming-setup

jeremylongshore

Implement streaming responses with OpenRouter. Use when building real-time chat interfaces or reducing time-to-first-token. Trigger with phrases like 'openrouter streaming', 'openrouter sse', 'stream response', 'real-time openrouter'.

111

perplexity-multi-env-setup

jeremylongshore

Configure Perplexity across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific Perplexity configurations. Trigger with phrases like "perplexity environments", "perplexity staging", "perplexity dev prod", "perplexity environment setup", "perplexity config by env".

210

Search skills

Search the agent skills registry