instantly-performance-tuning

0
0
Source

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

Install

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

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

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.

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.

6532

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.

9029

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".

15922

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.

4915

designing-database-schemas

jeremylongshore

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

12014

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.

5110

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,4071,302

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.

1,2201,024

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."

9001,013

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.

958658

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.

970608

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.

1,033496

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.