customerio-performance-tuning

3
1
Source

Optimize Customer.io API performance. Use when improving response times, reducing latency, or optimizing high-volume integrations. Trigger with phrases like "customer.io performance", "optimize customer.io", "customer.io latency", "customer.io speed".

Install

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

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

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.

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.

11036

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.

9033

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

18828

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.

5519

designing-database-schemas

jeremylongshore

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

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

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,6841,428

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

1,2611,321

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,5311,146

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.

1,350807

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.

1,263727

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,478682