IN

instantly-performance-tuning

Techniques for optimizing Instantly.ai API throughput using caching, batching, and concurrent request management.

Install

mkdir -p .claude/skills/instantly-performance-tuning && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/9209" && unzip -o skill.zip -d .claude/skills/instantly-performance-tuning && rm skill.zip

Installs to .claude/skills/instantly-performance-tuning

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.

Optimize Instantly.ai API performance with caching, batching, and connection
76 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Cache campaign analytics data
  • Batch lead operations with concurrency control
  • Implement cursor-based pagination
  • Manage connection reuse with Keep-Alive
  • Throttle email listing requests

How it works

This skill provides TypeScript patterns to minimize API load through caching and manages throughput using controlled concurrency and request throttling.

Inputs & outputs

You give it
Lead data array and campaign ID
You get back
Batch processing result with success and failure logs

When to use instantly-performance-tuning

  • Caching campaign analytics to reduce API load
  • Batching lead operations to increase throughput
  • Managing concurrent requests to avoid rate limits
  • Optimizing pagination for large datasets

About this skill

Instantly Performance Tuning

Overview

Optimize Instantly API v2 integrations for speed and throughput. Key areas: caching analytics data, batching lead operations, concurrent request management, efficient pagination, and connection reuse. The email listing endpoint has a strict 20 req/min limit that requires special handling.

Prerequisites

  • Completed instantly-install-auth setup
  • Working Instantly integration
  • Understanding of async patterns and caching strategies

Instructions

Step 1: Cache Analytics Data

Campaign analytics don't change every second — cache them for 5-15 minutes to avoid redundant API calls.

class InstantlyCache {
  private cache = new Map<string, { data: unknown; expiry: number }>();

  get<T>(key: string): T | null {
    const entry = this.cache.get(key);
    if (!entry || Date.now() > entry.expiry) {
      this.cache.delete(key);
      return null;
    }
    return entry.data as T;
  }

  set(key: string, data: unknown, ttlMs: number) {
    this.cache.set(key, { data, expiry: Date.now() + ttlMs });
  }
}

const cache = new InstantlyCache();

async function getCachedAnalytics(campaignId: string) {
  const cacheKey = `analytics:${campaignId}`;
  const cached = cache.get<CampaignAnalytics>(cacheKey);
  if (cached) return cached;

  const data = await instantly<CampaignAnalytics>(
    `/campaigns/analytics?id=${campaignId}`
  );
  cache.set(cacheKey, data, 5 * 60 * 1000); // 5 min TTL
  return data;
}

// Cache campaign list (changes infrequently)
async function getCachedCampaigns() {
  const cacheKey = "campaigns:all";
  const cached = cache.get<Campaign[]>(cacheKey);
  if (cached) return cached;

  const campaigns = await instantly<Campaign[]>("/campaigns?limit=100");
  cache.set(cacheKey, campaigns, 15 * 60 * 1000); // 15 min TTL
  return campaigns;
}

Step 2: Batch Lead Operations with Controlled Concurrency

interface BatchResult<T> {
  succeeded: T[];
  failed: Array<{ input: unknown; error: string }>;
  duration: number;
}

async function batchAddLeads(
  campaignId: string,
  leads: Array<{ email: string; first_name?: string; company_name?: string }>,
  options = { concurrency: 5, delayMs: 200, retries: 3 }
): Promise<BatchResult<Lead>> {
  const start = Date.now();
  const succeeded: Lead[] = [];
  const failed: Array<{ input: unknown; error: string }> = [];
  let active = 0;

  const addWithRetry = async (lead: typeof leads[0]) => {
    for (let attempt = 0; attempt <= options.retries; attempt++) {
      try {
        const result = await instantly<Lead>("/leads", {
          method: "POST",
          body: JSON.stringify({
            campaign: campaignId,
            email: lead.email,
            first_name: lead.first_name,
            company_name: lead.company_name,
            skip_if_in_workspace: true,
          }),
        });
        succeeded.push(result);
        return;
      } catch (err: any) {
        if (err.status === 429) {
          await new Promise((r) => setTimeout(r, Math.pow(2, attempt) * 1000));
          continue;
        }
        if (attempt === options.retries) {
          failed.push({ input: lead, error: err.message });
        }
      }
    }
  };

  // Process in chunks
  for (let i = 0; i < leads.length; i += options.concurrency) {
    const chunk = leads.slice(i, i + options.concurrency);
    await Promise.allSettled(chunk.map(addWithRetry));

    if (i + options.concurrency < leads.length) {
      await new Promise((r) => setTimeout(r, options.delayMs));
    }

    // Progress report
    const progress = Math.min(i + options.concurrency, leads.length);
    console.log(`Progress: ${progress}/${leads.length} (${succeeded.length} ok, ${failed.length} failed)`);
  }

  return { succeeded, failed, duration: Date.now() - start };
}

Step 3: Efficient Pagination

// Pre-fetch next page while processing current page
async function* prefetchPaginate<T extends { id: string }>(
  path: string,
  pageSize = 100
): AsyncGenerator<T[]> {
  let startingAfter: string | undefined;
  let nextPagePromise: Promise<T[]> | null = null;

  const fetchPage = (after?: string) => {
    const qs = new URLSearchParams({ limit: String(pageSize) });
    if (after) qs.set("starting_after", after);
    return instantly<T[]>(`${path}?${qs}`);
  };

  // Fetch first page
  let currentPage = await fetchPage();

  while (currentPage.length > 0) {
    // Start fetching next page immediately
    if (currentPage.length === pageSize) {
      const lastId = currentPage[currentPage.length - 1].id;
      nextPagePromise = fetchPage(lastId);
    } else {
      nextPagePromise = null;
    }

    yield currentPage;

    if (!nextPagePromise) break;
    currentPage = await nextPagePromise;
  }
}

// Usage — processes next page while current page is being handled
for await (const batch of prefetchPaginate<Lead>("/leads/list")) {
  for (const lead of batch) {
    // Process lead — next page is already loading
  }
}

Step 4: Connection Reuse with Keep-Alive

import { Agent } from "undici";

// Create a persistent connection pool
const dispatcher = new Agent({
  keepAliveTimeout: 30000,     // keep connections alive for 30s
  keepAliveMaxTimeout: 60000,
  connections: 10,             // max 10 concurrent connections
  pipelining: 1,
});

async function instantlyPooled<T>(path: string, options: RequestInit = {}): Promise<T> {
  const url = `https://api.instantly.ai/api/v2${path}`;
  const res = await fetch(url, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.INSTANTLY_API_KEY}`,
      ...options.headers,
    },
    // @ts-ignore — undici dispatcher
    dispatcher,
  });

  if (!res.ok) throw new Error(`Instantly ${res.status}: ${await res.text()}`);
  return res.json() as Promise<T>;
}

Step 5: Throttled Email Fetcher (20 req/min limit)

class ThrottledEmailClient {
  private timestamps: number[] = [];
  private readonly maxPerMinute = 18; // leave margin

  private async throttle() {
    const now = Date.now();
    this.timestamps = this.timestamps.filter((t) => now - t < 60000);

    if (this.timestamps.length >= this.maxPerMinute) {
      const wait = 60000 - (now - this.timestamps[0]) + 500;
      await new Promise((r) => setTimeout(r, wait));
    }
    this.timestamps.push(Date.now());
  }

  async listEmails(params: { campaign_id?: string; limit?: number; starting_after?: string }) {
    await this.throttle();
    const qs = new URLSearchParams();
    if (params.campaign_id) qs.set("campaign_id", params.campaign_id);
    if (params.limit) qs.set("limit", String(params.limit));
    if (params.starting_after) qs.set("starting_after", params.starting_after);
    return instantly(`/emails?${qs}`);
  }

  async getUnreadCount() {
    await this.throttle();
    return instantly("/emails/unread/count");
  }
}

Performance Benchmarks

OperationUnoptimizedOptimizedImprovement
500 lead import~250s (sequential)~30s (5 concurrent + batch)8x
Campaign analytics (10 queries)10 API calls1 API call (cached)10x
All campaigns page load~2s (no cache)~50ms (cached)40x
Lead pagination (10K leads)~100s (sequential)~50s (prefetch)2x

Error Handling

ErrorCauseSolution
429 during batch importToo many concurrent requestsReduce concurrency, increase delay
429 on email listing>20 req/minUse ThrottledEmailClient
Stale cache dataTTL too longReduce TTL or add cache invalidation
Memory issuesLarge pagination result setUse async generators, process in chunks

Resources

Next Steps

For cost optimization, see instantly-cost-tuning.

When not to use it

  • When cache TTL is too long for real-time data needs
  • When API rate limits are not a concern

Prerequisites

instantly-install-auth setupWorking Instantly integration

Limitations

  • Email listing endpoint has a strict 20 req/min limit
  • Stale cache data if TTL is not managed

How it compares

It replaces sequential, unmanaged API calls with optimized patterns like pre-fetching and rate-limit-aware batching.

Compared to similar skills

instantly-performance-tuning side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
instantly-performance-tuning (this skill)027dCautionIntermediate
documenso-performance-tuning027dReviewIntermediate
gamma-performance-tuning027dNo flagsIntermediate
juicebox-prod-checklist127dCautionBeginner

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

documenso-performance-tuning

jeremylongshore

Optimize Documenso integration performance with caching, batching, and efficient patterns. Use when improving response times, reducing API calls, or optimizing bulk document operations. Trigger with phrases like "documenso performance", "optimize documenso", "documenso caching", "documenso batch operations".

01

gamma-performance-tuning

jeremylongshore

Optimize Gamma API performance and reduce latency. Use when experiencing slow response times, optimizing throughput, or improving user experience with Gamma integrations. Trigger with phrases like "gamma performance", "gamma slow", "gamma latency", "gamma optimization", "gamma speed".

01

juicebox-prod-checklist

jeremylongshore

Execute Juicebox production deployment checklist. Use when preparing for production launch, validating deployment readiness, or performing pre-launch reviews. Trigger with phrases like "juicebox production", "deploy juicebox prod", "juicebox launch checklist", "juicebox go-live".

10

perplexity-architecture-variants

jeremylongshore

Choose and implement Perplexity validated architecture blueprints for different scales. Use when designing new Perplexity integrations, choosing between monolith/service/microservice architectures, or planning migration paths for Perplexity applications. Trigger with phrases like "perplexity architecture", "perplexity blueprint", "how to structure perplexity", "perplexity project layout", "perplexity microservice".

00

idmp

ha0z1

Use when you need to deduplicate concurrent or repeated async calls, prevent duplicate API requests, cache async function results, add automatic retry with exponential backoff, memoize heavy computation wrapped in Promise, replace SWR/Provider for request sharing, invalidate cache with flush, or per

00

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

Search skills

Search the agent skills registry