customerio-cost-tuning

0
0
Source

Optimize Customer.io costs and usage. Use when reducing expenses, optimizing usage, or right-sizing your Customer.io plan. Trigger with phrases like "customer.io cost", "reduce customer.io spend", "customer.io billing", "customer.io pricing".

Install

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

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

About this skill

Customer.io Cost Tuning

Overview

Optimize Customer.io costs by managing profile count (the primary billing driver), suppressing/deleting inactive users, deduplicating events, reducing unnecessary API calls, and monitoring usage trends.

How Customer.io Pricing Works

Customer.io bills based on profile count (number of identified people in your workspace) and email/SMS volume. Key cost drivers:

FactorImpactOptimization Strategy
Total profilesPrimary cost driverDelete inactive profiles
Email sendsPer-email cost above tierSuppress unengaged users
SMS sendsPer-SMS costOnly send to opt-in users
OveridentificationCreates unnecessary profilesDon't identify users who'll never receive messages
Event volumeCan increase processing costsDeduplicate and sample

Instructions

Step 1: Profile Audit

// scripts/cio-profile-audit.ts
// Audit your Customer.io integration for cost optimization opportunities

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

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

// Check: Are you identifying users who'll never receive messages?
const AUDIT_RULES = {
  // Users without email can't receive email campaigns
  noEmail: "Don't identify users without email unless using push/SMS",

  // Test users should be cleaned up
  testUsers: "Suppress and delete test-*, ci-*, dev-* prefixed users",

  // Anonymous users that never convert inflate profile count
  staleAnonymous: "Delete anonymous profiles older than 90 days without conversion",

  // Inactive users who haven't opened email in 6+ months
  unengaged: "Suppress users with no email opens in 180+ days",
};

console.log("=== Customer.io Cost Audit Rules ===\n");
for (const [rule, action] of Object.entries(AUDIT_RULES)) {
  console.log(`${rule}: ${action}`);
}
console.log("\nRun these checks in Customer.io dashboard:");
console.log("1. People > Segments > Create 'Inactive 90 days' segment");
console.log("2. People > Segments > Create 'No email attribute' segment");
console.log("3. People > Filter by created_at < 90 days ago AND email_opened = 0");

Step 2: Suppress and Delete Inactive Users

// scripts/cio-cleanup-inactive.ts
import { TrackClient, RegionUS } from "customerio-node";

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

interface CleanupTarget {
  userId: string;
  reason: string;
}

async function cleanupInactiveUsers(
  targets: CleanupTarget[],
  dryRun: boolean = true
): Promise<void> {
  let suppressed = 0;
  let deleted = 0;
  let errors = 0;

  for (const target of targets) {
    if (dryRun) {
      console.log(`[DRY RUN] Would suppress+delete: ${target.userId} (${target.reason})`);
      continue;
    }

    try {
      // Step 1: Suppress — stops all messaging immediately
      await cio.suppress(target.userId);
      suppressed++;

      // Step 2: Destroy — removes from billing
      await cio.destroy(target.userId);
      deleted++;

      // Rate limit to 50/sec for bulk operations
      await new Promise((r) => setTimeout(r, 20));
    } catch (err: any) {
      errors++;
      console.error(`Failed ${target.userId}: ${err.message}`);
    }

    if ((suppressed + errors) % 100 === 0) {
      console.log(`Progress: ${suppressed} deleted, ${errors} errors`);
    }
  }

  console.log(`\nResult: ${suppressed} suppressed, ${deleted} deleted, ${errors} errors`);
}

// Usage: Build target list from your database
// const inactiveUsers = await db.query(`
//   SELECT id FROM users
//   WHERE last_login_at < NOW() - INTERVAL '180 days'
//   AND email_verified = false
// `);

Step 3: Event Deduplication

// lib/customerio-dedup-events.ts
// Prevent sending duplicate events that inflate volume

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

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

// Simple LRU dedup (use Redis in production)
const recentEvents = new Map<string, number>();
const MAX_CACHE = 50_000;
const DEDUP_WINDOW_MS = 60 * 1000;  // 1 minute window

function isDuplicate(userId: string, eventName: string, data?: any): boolean {
  const hash = createHash("sha256")
    .update(`${userId}:${eventName}:${JSON.stringify(data ?? {})}`)
    .digest("hex")
    .substring(0, 12);

  const last = recentEvents.get(hash);
  if (last && Date.now() - last < DEDUP_WINDOW_MS) {
    return true;
  }

  recentEvents.set(hash, Date.now());

  // Prevent unbounded growth
  if (recentEvents.size > MAX_CACHE) {
    const cutoff = Date.now() - DEDUP_WINDOW_MS;
    for (const [key, time] of recentEvents) {
      if (time < cutoff) recentEvents.delete(key);
    }
  }

  return false;
}

export async function trackDeduped(
  userId: string,
  name: string,
  data?: Record<string, any>
): Promise<void> {
  if (isDuplicate(userId, name, data)) {
    return; // Skip duplicate
  }
  await cio.track(userId, { name, data });
}

Step 4: Event Sampling for High-Volume Events

// lib/customerio-sampling.ts
// Sample high-volume events to reduce API calls

const EVENT_SAMPLE_RATES: Record<string, number> = {
  page_viewed: 0.1,          // Sample 10% of page views
  button_clicked: 0.25,      // Sample 25% of clicks
  search_performed: 0.5,     // Sample 50% of searches
  signed_up: 1.0,            // Always track signups
  checkout_completed: 1.0,   // Always track purchases
  subscription_cancelled: 1.0, // Always track cancellations
};

export function shouldTrack(eventName: string): boolean {
  const rate = EVENT_SAMPLE_RATES[eventName] ?? 1.0;
  return Math.random() < rate;
}

// Usage
if (shouldTrack("page_viewed")) {
  await cio.track(userId, {
    name: "page_viewed",
    data: { url: "/pricing", sampled: true },
  });
}

Step 5: Usage Monitoring

// scripts/cio-usage-monitor.ts
// Track your Customer.io usage trends

interface UsageMetrics {
  identifyCalls: number;
  trackCalls: number;
  transactionalSends: number;
  broadcastTriggers: number;
  webhooksReceived: number;
}

class UsageMonitor {
  private metrics: UsageMetrics = {
    identifyCalls: 0,
    trackCalls: 0,
    transactionalSends: 0,
    broadcastTriggers: 0,
    webhooksReceived: 0,
  };

  increment(metric: keyof UsageMetrics): void {
    this.metrics[metric]++;
  }

  report(): void {
    console.log("\n=== Customer.io Usage Report ===");
    console.log(`Period: ${new Date().toISOString()}`);
    for (const [key, value] of Object.entries(this.metrics)) {
      console.log(`  ${key}: ${value.toLocaleString()}`);
    }
    const total = Object.values(this.metrics).reduce((a, b) => a + b, 0);
    console.log(`  TOTAL API calls: ${total.toLocaleString()}`);
  }

  reset(): void {
    for (const key of Object.keys(this.metrics)) {
      this.metrics[key as keyof UsageMetrics] = 0;
    }
  }
}

export const usageMonitor = new UsageMonitor();

Cost Savings Estimates

OptimizationTypical SavingsImplementation Effort
Delete inactive profiles (180+ days)15-30% profile costLow
Event deduplication5-15% event volumeLow
Event sampling (analytics events)50-80% event volume for sampled eventsLow
Suppress bounced emails2-5% email costLow
Don't identify email-less users5-20% profile costMedium
Annual billing10-20% total costNone

Monthly Cost Review Checklist

  • Review profile count trend (People > Overview)
  • Identify and delete stale test profiles
  • Review segment for users with no email attribute
  • Check bounce rate and suppress chronic bouncers
  • Review event volume by type (optimize high-volume/low-value events)
  • Compare plan tier vs actual usage

Resources

Next Steps

After cost optimization, proceed to customerio-reference-architecture for enterprise patterns.

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.