CU

customerio-performance-tuning

Provides techniques to improve Customer.io API response times and reduce integration latency.

Install

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

Installs to .claude/skills/customerio-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 Customer.io API performance for high throughput.
57 charsno explicit “when” trigger
Advanced

Key capabilities

  • Implement HTTP connection pooling for Customer.io
  • Cache and deduplicate identify calls
  • Batch Customer.io event tracking requests
  • Implement fire-and-forget async tracking
  • Route API calls to regional Customer.io endpoints
  • Monitor Customer.io API call latency

How it works

The skill provides code examples and instructions to optimize Customer.io API performance by reusing HTTP connections, deduplicating identify calls, batching events, and using asynchronous tracking.

Inputs & outputs

You give it
Customer.io API calls and integration code
You get back
Improved Customer.io API response times and reduced latency

When to use customerio-performance-tuning

  • Implementing connection pooling
  • Batching event tracking requests
  • Reducing API call latency
  • Caching deduplication for identify events

About this skill

Customer.io Performance Tuning

Overview

Optimize Customer.io API performance for high-volume integrations: HTTP connection pooling, identify deduplication caching, event batching with flush control, fire-and-forget async tracking, and regional routing.

Prerequisites

  • Working Customer.io integration
  • Understanding of your traffic patterns and volume
  • Monitoring to measure improvement (see customerio-observability)

Performance Targets

OperationBaselineOptimizedTechnique
Single identify~200ms~80msConnection pooling
Single track~200ms~80msConnection pooling
100 events batch~20s serial~500msParallel batching
Duplicate identify~200ms~0msDedup cache
Non-critical trackBlockingNon-blockingFire-and-forget

Instructions

Step 1: HTTP Connection Pooling

// lib/customerio-pooled.ts
import { TrackClient, RegionUS } from "customerio-node";
import https from "https";

// The customerio-node SDK creates new connections by default.
// Reuse connections with a keep-alive agent.
const agent = new https.Agent({
  keepAlive: true,
  maxSockets: 25,        // Max concurrent connections
  maxFreeSockets: 10,    // Keep idle connections open
  timeout: 30000,        // 30s socket timeout
  keepAliveMsecs: 15000, // TCP keep-alive probe interval
});

// Apply to the SDK by creating a singleton with the agent
// Note: customerio-node doesn't directly accept an agent,
// but we configure Node.js global agent for HTTPS
https.globalAgent = agent;

// Singleton client — one instance = one connection pool
const cio = new TrackClient(
  process.env.CUSTOMERIO_SITE_ID!,
  process.env.CUSTOMERIO_TRACK_API_KEY!,
  { region: RegionUS }
);

export { cio };

Step 2: Identify Deduplication Cache

// lib/customerio-dedup.ts
// Skip duplicate identify() calls within a time window

class LRUCache<K, V> {
  private map = new Map<K, V>();
  constructor(private maxSize: number) {}

  get(key: K): V | undefined {
    const val = this.map.get(key);
    if (val !== undefined) {
      // Move to end (most recent)
      this.map.delete(key);
      this.map.set(key, val);
    }
    return val;
  }

  set(key: K, val: V): void {
    this.map.delete(key);
    this.map.set(key, val);
    if (this.map.size > this.maxSize) {
      const oldest = this.map.keys().next().value;
      this.map.delete(oldest!);
    }
  }
}

import { createHash } from "crypto";
import { TrackClient, RegionUS } from "customerio-node";

const identifyCache = new LRUCache<string, number>(10_000);
const DEDUP_TTL_MS = 5 * 60 * 1000;  // 5 minutes

const cio = new TrackClient(
  process.env.CUSTOMERIO_SITE_ID!,
  process.env.CUSTOMERIO_TRACK_API_KEY!,
  { region: RegionUS }
);

export async function dedupIdentify(
  userId: string,
  attrs: Record<string, any>
): Promise<void> {
  // Create a hash of userId + attributes
  const hash = createHash("sha256")
    .update(userId + JSON.stringify(attrs))
    .digest("hex")
    .substring(0, 16);

  const cached = identifyCache.get(hash);
  if (cached && Date.now() - cached < DEDUP_TTL_MS) {
    return; // Skip — identical identify() call within TTL window
  }

  await cio.identify(userId, attrs);
  identifyCache.set(hash, Date.now());
}

Step 3: Batch Processor

// lib/customerio-batch.ts
import { TrackClient, RegionUS } from "customerio-node";

interface BatchItem {
  type: "identify" | "track";
  userId: string;
  data: Record<string, any>;
}

export class CioBatchProcessor {
  private buffer: BatchItem[] = [];
  private timer: NodeJS.Timeout | null = null;
  private client: TrackClient;
  private processing = false;

  constructor(
    private readonly maxBatchSize = 100,
    private readonly flushIntervalMs = 3000,
    private readonly concurrency = 15
  ) {
    this.client = new TrackClient(
      process.env.CUSTOMERIO_SITE_ID!,
      process.env.CUSTOMERIO_TRACK_API_KEY!,
      { region: RegionUS }
    );
    this.startFlushTimer();
  }

  add(item: BatchItem): void {
    this.buffer.push(item);
    if (this.buffer.length >= this.maxBatchSize) {
      this.flush();
    }
  }

  async flush(): Promise<void> {
    if (this.processing || this.buffer.length === 0) return;
    this.processing = true;

    const batch = this.buffer.splice(0, this.maxBatchSize);
    const startMs = Date.now();

    // Process in parallel chunks
    for (let i = 0; i < batch.length; i += this.concurrency) {
      const chunk = batch.slice(i, i + this.concurrency);
      const results = await Promise.allSettled(
        chunk.map((item) =>
          item.type === "identify"
            ? this.client.identify(item.userId, item.data)
            : this.client.track(item.userId, item.data)
        )
      );

      const failed = results.filter((r) => r.status === "rejected").length;
      if (failed > 0) {
        console.warn(`CIO batch: ${failed}/${chunk.length} failed`);
      }
    }

    const elapsed = Date.now() - startMs;
    console.log(`CIO batch: ${batch.length} items in ${elapsed}ms`);
    this.processing = false;
  }

  private startFlushTimer(): void {
    this.timer = setInterval(() => this.flush(), this.flushIntervalMs);
  }

  async shutdown(): Promise<void> {
    if (this.timer) clearInterval(this.timer);
    await this.flush();
  }
}

Step 4: Fire-and-Forget Async Tracking

// lib/customerio-async.ts
// For non-critical analytics events — don't block the request path

import { TrackClient, RegionUS } from "customerio-node";

const cio = new TrackClient(
  process.env.CUSTOMERIO_SITE_ID!,
  process.env.CUSTOMERIO_TRACK_API_KEY!,
  { region: RegionUS }
);

export function fireAndForgetTrack(
  userId: string,
  eventName: string,
  data?: Record<string, any>
): void {
  // No await — returns immediately
  cio
    .track(userId, { name: eventName, data })
    .catch((err) => console.error(`CIO async track failed: ${err.message}`));
}

// Usage in Express route — does NOT slow down response
router.get("/dashboard", async (req, res) => {
  fireAndForgetTrack(req.user.id, "dashboard_viewed", {
    timestamp: Math.floor(Date.now() / 1000),
  });

  const data = await loadDashboardData(req.user.id);
  res.json(data);  // Returns immediately without waiting for CIO
});

Step 5: Regional Routing

// lib/customerio-region.ts
import { TrackClient, APIClient, RegionUS, RegionEU } from "customerio-node";

// Route to nearest Customer.io region based on configuration
// US accounts: track.customer.io / api.customer.io
// EU accounts: track-eu.customer.io / api-eu.customer.io

interface CioRegionalConfig {
  us: { siteId: string; trackKey: string; appKey: string };
  eu: { siteId: string; trackKey: string; appKey: string };
}

function getClientForUser(
  config: CioRegionalConfig,
  userRegion: "us" | "eu"
): { track: TrackClient; api: APIClient } {
  const creds = config[userRegion];
  const region = userRegion === "eu" ? RegionEU : RegionUS;

  return {
    track: new TrackClient(creds.siteId, creds.trackKey, { region }),
    api: new APIClient(creds.appKey, { region }),
  };
}

Performance Monitoring

// Wrap operations to measure latency
async function timedCioCall<T>(
  operation: string,
  fn: () => Promise<T>
): Promise<T> {
  const start = Date.now();
  try {
    const result = await fn();
    const elapsed = Date.now() - start;
    console.log(`CIO ${operation}: ${elapsed}ms`);
    return result;
  } catch (err) {
    const elapsed = Date.now() - start;
    console.error(`CIO ${operation} FAILED: ${elapsed}ms`);
    throw err;
  }
}

Error Handling

IssueSolution
High p99 latencyEnable connection pooling, check DNS resolution
Timeout errorsIncrease timeout, reduce payload size
Memory growthCap LRU cache size, limit batch buffer
Dedup cache missesIncrease TTL if same identify calls are >5min apart

Resources

Next Steps

After performance tuning, proceed to customerio-cost-tuning for cost optimization.

When not to use it

  • When a working Customer.io integration is not present
  • When traffic patterns and volume are unknown

Prerequisites

Working Customer.io integrationUnderstanding of your traffic patterns and volumeMonitoring to measure improvement (see `customerio-observability`)

Limitations

  • Requires a working Customer.io integration
  • Requires understanding of traffic patterns and volume
  • Requires monitoring to measure improvement

How it compares

This skill offers specific code implementations for Customer.io API optimization, which is more targeted than general performance tuning advice.

Compared to similar skills

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

SkillInstallsUpdatedSafetyDifficulty
customerio-performance-tuning (this skill)127dReviewAdvanced
deepgram-performance-tuning327dReviewIntermediate
graphql66moNo flagsAdvanced
guidewire-sdk-patterns227dReviewAdvanced

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