intercom-performance-tuning
Optimize Intercom API performance with caching, search optimization, and pagination. Use when experiencing slow API responses, implementing caching strategies, or optimizing request throughput for Intercom integrations. Trigger with phrases like "intercom performance", "optimize intercom", "intercom latency", "intercom caching", "intercom slow", "intercom pagination".
What this skill does
# Intercom Performance Tuning
## Overview
Optimize Intercom API performance through response caching, efficient search queries, cursor-based pagination, connection pooling, and request batching.
## Prerequisites
- `intercom-client` SDK installed
- Understanding of Intercom data model
- Redis or in-memory cache available (optional)
## Intercom API Latency Baselines
| Operation | Typical P50 | Typical P95 | Notes |
|-----------|-------------|-------------|-------|
| `GET /me` (health check) | 50ms | 150ms | Lightest endpoint |
| `GET /contacts/{id}` | 80ms | 200ms | Single lookup |
| `POST /contacts/search` | 120ms | 400ms | Depends on query complexity |
| `GET /conversations/{id}` | 100ms | 300ms | Heavier with parts (up to 500) |
| `POST /contacts` (create) | 150ms | 400ms | Write operation |
| `GET /contacts` (list) | 100ms | 350ms | Paginated, 50 per page |
| `POST /messages` | 200ms | 500ms | Triggers delivery pipeline |
## Instructions
### Step 1: Response Caching
Cache frequently accessed contacts and conversations to avoid repeated API calls.
```typescript
import { LRUCache } from "lru-cache";
import { IntercomClient } from "intercom-client";
import { Intercom } from "intercom-client";
const contactCache = new LRUCache<string, Intercom.Contact>({
max: 5000,
ttl: 5 * 60 * 1000, // 5 minutes
});
const client = new IntercomClient({
token: process.env.INTERCOM_ACCESS_TOKEN!,
});
async function getContact(contactId: string): Promise<Intercom.Contact> {
const cached = contactCache.get(contactId);
if (cached) return cached;
const contact = await client.contacts.find({ contactId });
contactCache.set(contactId, contact);
return contact;
}
// Invalidate on update
async function updateContact(
contactId: string,
data: Partial<Intercom.UpdateContactRequest>
): Promise<Intercom.Contact> {
contactCache.delete(contactId);
const updated = await client.contacts.update({ contactId, ...data });
contactCache.set(contactId, updated);
return updated;
}
// Webhook-driven cache invalidation
function handleContactWebhook(notification: any): void {
const contactId = notification.data?.item?.id;
if (contactId) {
contactCache.delete(contactId);
}
}
```
### Step 2: Efficient Search Queries
Minimize search latency by using selective queries and limiting fields.
```typescript
// BAD: Overly broad search, fetching too many results
const allUsers = await client.contacts.search({
query: { field: "role", operator: "=", value: "user" },
pagination: { per_page: 150 }, // Max is 150
});
// GOOD: Targeted search with specific filters
const recentPro = await client.contacts.search({
query: {
operator: "AND",
value: [
{ field: "role", operator: "=", value: "user" },
{ field: "custom_attributes.plan", operator: "=", value: "pro" },
{ field: "last_seen_at", operator: ">", value: Math.floor(Date.now() / 1000) - 86400 },
],
},
pagination: { per_page: 25 },
sort: { field: "last_seen_at", order: "descending" },
});
```
### Step 3: Optimized Pagination
```typescript
// Stream contacts with memory-efficient cursor pagination
async function* streamContacts(
client: IntercomClient,
perPage = 50
): AsyncGenerator<Intercom.Contact> {
let startingAfter: string | undefined;
do {
const page = await client.contacts.list({ perPage, startingAfter });
for (const contact of page.data) {
yield contact;
}
startingAfter = page.pages?.next?.startingAfter ?? undefined;
// Small delay to avoid rate limits on large datasets
if (startingAfter) {
await new Promise(r => setTimeout(r, 100));
}
} while (startingAfter);
}
// Process contacts in batches for efficiency
async function processContactsInBatches(
client: IntercomClient,
processor: (contacts: Intercom.Contact[]) => Promise<void>,
batchSize = 100
): Promise<number> {
let batch: Intercom.Contact[] = [];
let total = 0;
for await (const contact of streamContacts(client)) {
batch.push(contact);
if (batch.length >= batchSize) {
await processor(batch);
total += batch.length;
batch = [];
}
}
if (batch.length > 0) {
await processor(batch);
total += batch.length;
}
return total;
}
```
### Step 4: Connection Pooling
```typescript
import { Agent } from "https";
// Reuse TCP connections (HTTP keep-alive)
const agent = new Agent({
keepAlive: true,
maxSockets: 10, // Max concurrent connections
maxFreeSockets: 5, // Keep idle connections warm
timeout: 30000, // Connection timeout
});
// Apply to fetch calls if using raw API
const response = await fetch("https://api.intercom.io/contacts", {
headers: { Authorization: `Bearer ${token}` },
agent,
} as any);
```
### Step 5: Parallel Requests with Rate Awareness
```typescript
import PQueue from "p-queue";
const queue = new PQueue({
concurrency: 5, // Max parallel requests
interval: 1000, // Per second
intervalCap: 100, // Max per interval
});
// Batch-lookup contacts by ID
async function getContactsBatch(
client: IntercomClient,
contactIds: string[]
): Promise<Map<string, Intercom.Contact>> {
const results = new Map<string, Intercom.Contact>();
await Promise.all(
contactIds.map(id =>
queue.add(async () => {
// Check cache first
const cached = contactCache.get(id);
if (cached) {
results.set(id, cached);
return;
}
try {
const contact = await client.contacts.find({ contactId: id });
contactCache.set(id, contact);
results.set(id, contact);
} catch {
// Skip not-found contacts
}
})
)
);
return results;
}
```
### Step 6: Performance Monitoring
```typescript
async function measuredCall<T>(
name: string,
operation: () => Promise<T>
): Promise<T> {
const start = performance.now();
try {
const result = await operation();
const duration = performance.now() - start;
console.log(JSON.stringify({
metric: "intercom.api.call",
operation: name,
duration_ms: Math.round(duration),
status: "success",
}));
return result;
} catch (error) {
const duration = performance.now() - start;
console.error(JSON.stringify({
metric: "intercom.api.call",
operation: name,
duration_ms: Math.round(duration),
status: "error",
error: (error as Error).message,
}));
throw error;
}
}
// Usage
const contact = await measuredCall("contacts.find", () =>
client.contacts.find({ contactId: "abc123" })
);
```
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Cache stampede | Many concurrent cache misses | Use mutex/lock per key |
| Memory pressure | Cache too large | Set `max` on LRUCache |
| Stale data | TTL too long | Use webhook invalidation |
| Pagination timeouts | Large data set + slow network | Reduce per_page, add delays |
| Rate limit during batch | Too many parallel requests | Lower PQueue concurrency |
## Resources
- [Pagination](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination)
- [Search Contacts](https://developers.intercom.com/docs/references/rest-api/api.intercom.io/contacts/searchcontacts)
- [LRU Cache](https://github.com/isaacs/node-lru-cache)
- [p-queue](https://github.com/sindresorhus/p-queue)
## Next Steps
For cost optimization, see `intercom-cost-tuning`.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.