customerio-sdk-patterns
Customer.ioのSDKパターンを本番環境対応で適用できます。ベストプラクティスの実装、統合の見直し、またはアプリケーション内のCustomer.io利用の最適化が必要な場合に使用してください。「customer.io best practices」「customer.io patterns」「production customer.io」「customer.io architecture」といったフレーズでトリガーされます。
description の原文を見る
Apply production-ready Customer.io SDK patterns. Use when implementing best practices, refactoring integrations, or optimizing Customer.io usage in your application. Trigger with phrases like "customer.io best practices", "customer.io patterns", "production customer.io", "customer.io architecture".
SKILL.md 本文
Customer.io SDK パターン
概要
エラーハンドリング、バッチ処理、型安全性を含むCustomer.io SDKの本番環境対応パターン集。
前提条件
- Customer.io SDKがインストールされていること
- TypeScriptプロジェクト(推奨)
- async/awaitパターンの理解
手順
パターン1: 型安全なクライアント
// types/customerio.ts
export interface UserAttributes {
email: string;
first_name?: string;
last_name?: string;
created_at?: number;
plan?: 'free' | 'pro' | 'enterprise';
[key: string]: string | number | boolean | undefined;
}
export interface EventData {
[key: string]: string | number | boolean | object;
}
export type EventName =
| 'signed_up'
| 'subscription_started'
| 'subscription_cancelled'
| 'feature_used'
| 'email_verified';
// lib/customerio-client.ts
import { TrackClient, RegionUS } from '@customerio/track';
import type { UserAttributes, EventData, EventName } from '../types/customerio';
export class TypedCustomerIO {
private client: TrackClient;
constructor() {
this.client = new TrackClient(
process.env.CUSTOMERIO_SITE_ID!,
process.env.CUSTOMERIO_API_KEY!,
{ region: RegionUS }
);
}
async identify(userId: string, attributes: UserAttributes): Promise<void> {
await this.client.identify(userId, {
...attributes,
_updated_at: Math.floor(Date.now() / 1000)
});
}
async track(userId: string, event: EventName, data?: EventData): Promise<void> {
await this.client.track(userId, { name: event, data });
}
}
パターン2: 指数バックオフを用いたリトライ
// lib/customerio-resilient.ts
import { TrackClient } from '@customerio/track';
interface RetryConfig {
maxRetries: number;
baseDelay: number;
maxDelay: number;
}
const defaultRetryConfig: RetryConfig = {
maxRetries: 3,
baseDelay: 1000,
maxDelay: 10000
};
async function withRetry<T>(
operation: () => Promise<T>,
config: RetryConfig = defaultRetryConfig
): Promise<T> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
if (attempt === config.maxRetries) break;
// Don't retry on 4xx errors (client errors)
if (error instanceof Error && error.message.includes('4')) {
throw error;
}
const delay = Math.min(
config.baseDelay * Math.pow(2, attempt),
config.maxDelay
);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
export class ResilientCustomerIO {
private client: TrackClient;
constructor(siteId: string, apiKey: string) {
this.client = new TrackClient(siteId, apiKey, { region: RegionUS });
}
async identify(userId: string, attributes: Record<string, any>) {
return withRetry(() => this.client.identify(userId, attributes));
}
async track(userId: string, event: string, data?: Record<string, any>) {
return withRetry(() => this.client.track(userId, { name: event, data }));
}
}
パターン3: バッチ処理付きイベントキュー
// lib/customerio-queue.ts
interface QueuedEvent {
userId: string;
event: string;
data?: Record<string, any>;
timestamp: number;
}
export class CustomerIOQueue {
private queue: QueuedEvent[] = [];
private flushInterval: NodeJS.Timer | null = null;
private maxBatchSize = 100;
private flushIntervalMs = 5000;
constructor(private client: TrackClient) {
this.startAutoFlush();
}
enqueue(userId: string, event: string, data?: Record<string, any>) {
this.queue.push({
userId,
event,
data,
timestamp: Date.now()
});
if (this.queue.length >= this.maxBatchSize) {
this.flush();
}
}
async flush(): Promise<void> {
if (this.queue.length === 0) return;
const batch = this.queue.splice(0, this.maxBatchSize);
await Promise.allSettled(
batch.map(item =>
this.client.track(item.userId, {
name: item.event,
data: { ...item.data, _queued_at: item.timestamp }
})
)
);
}
private startAutoFlush() {
this.flushInterval = setInterval(() => this.flush(), this.flushIntervalMs);
}
async shutdown(): Promise<void> {
if (this.flushInterval) {
clearInterval(this.flushInterval);
}
await this.flush();
}
}
パターン4: 遅延初期化を用いたシングルトン
// lib/customerio-singleton.ts
import { TrackClient, RegionUS } from '@customerio/track';
let instance: TrackClient | null = null;
export function getCustomerIO(): TrackClient {
if (!instance) {
if (!process.env.CUSTOMERIO_SITE_ID || !process.env.CUSTOMERIO_API_KEY) {
throw new Error('Customer.io credentials not configured');
}
instance = new TrackClient(
process.env.CUSTOMERIO_SITE_ID,
process.env.CUSTOMERIO_API_KEY,
{ region: RegionUS }
);
}
return instance;
}
// Usage
import { getCustomerIO } from './lib/customerio-singleton';
await getCustomerIO().identify('user-123', { email: 'user@example.com' });
出力
- 型安全なCustomer.ioクライアント
- リトライ機能付きのレジリアントなエラーハンドリング
- 大量イベント対応のバッチ処理
- リソース効率化のためのシングルトンパターン
エラーハンドリング
| エラー | 原因 | 解決方法 |
|---|---|---|
| 型の不一致 | 無効な属性型 | TypeScriptインターフェースを使用 |
| キューオーバーフロー | イベントが多すぎる | フラッシュ頻度またはバッチサイズを増加 |
| リトライ枯渇 | 永続的な障害 | ネットワークと認証情報を確認 |
リソース
次のステップ
パターンを実装した後、customerio-primary-workflowに進んでメッセージングワークフローを実装します。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- Brmbobo
- リポジトリ
- Brmbobo/Web2podcast
- ライセンス
- MIT
- 最終更新
- 2026/1/26
Source: https://github.com/Brmbobo/Web2podcast / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。