salesforce-performance-tuning
Optimize Salesforce API performance with SOQL tuning, Composite API batching, and caching. Use when experiencing slow API responses, optimizing SOQL queries, or reducing API call count for Salesforce integrations. Trigger with phrases like "salesforce performance", "optimize salesforce", "salesforce latency", "salesforce caching", "salesforce slow", "SOQL optimization".
What this skill does
# Salesforce Performance Tuning
## Overview
Optimize Salesforce API performance: tune SOQL queries, minimize API calls using Composite/Collections APIs, implement metadata caching, and handle large result sets efficiently.
## Prerequisites
- jsforce connection configured
- Understanding of SOQL query plans
- Redis or in-memory cache available (optional)
- Access to Setup > API usage monitoring
## Instructions
### Step 1: SOQL Query Optimization
```typescript
// BAD: SELECT * equivalent — fetches all fields
const result = await conn.query('SELECT FIELDS(ALL) FROM Account LIMIT 100');
// GOOD: Only select fields you need
const result = await conn.query(`
SELECT Id, Name, Industry, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
LIMIT 100
`);
// BAD: Non-selective WHERE clause (full table scan)
const result = await conn.query("SELECT Id FROM Contact WHERE Title LIKE '%Engineer%'");
// GOOD: Use indexed fields in WHERE (Id, Name, CreatedDate, RecordType, lookup fields)
const result = await conn.query(`
SELECT Id, Name, Title
FROM Contact
WHERE AccountId = '001xxxxxxxxxxxx'
AND CreatedDate >= LAST_N_DAYS:30
LIMIT 200
`);
// Use relationship queries to avoid N+1 pattern
// BAD: Query Accounts, then query Contacts for each (N+1 API calls)
const accounts = await conn.query('SELECT Id FROM Account LIMIT 50');
for (const acct of accounts.records) {
await conn.query(`SELECT Id FROM Contact WHERE AccountId = '${acct.Id}'`);
// 50 extra API calls!
}
// GOOD: Single relationship query (1 API call)
const accountsWithContacts = await conn.query(`
SELECT Id, Name,
(SELECT Id, FirstName, LastName, Email FROM Contacts LIMIT 20)
FROM Account
WHERE Industry = 'Technology'
LIMIT 50
`);
```
### Step 2: Reduce API Call Count
```typescript
// STRATEGY 1: sObject Collections — 200 records per API call
// Instead of 100 individual creates = 100 API calls
const contacts = Array.from({ length: 100 }, (_, i) => ({
FirstName: `User${i}`,
LastName: `Test`,
Email: `user${i}@test.com`,
}));
await conn.sobject('Contact').create(contacts); // 1 API call
// STRATEGY 2: Composite API — 25 mixed operations per API call
// Create Account + Contact + Opportunity = 1 API call instead of 3
// See salesforce-core-workflow-b
// STRATEGY 3: queryMore for pagination — FREE (doesn't count as extra call)
let result = await conn.query('SELECT Id, Name FROM Contact');
let allRecords = [...result.records];
while (!result.done) {
result = await conn.queryMore(result.nextRecordsUrl!);
allRecords.push(...result.records);
}
```
### Step 3: Cache Metadata (Describe Calls)
```typescript
import { LRUCache } from 'lru-cache';
// Describe calls are expensive and metadata rarely changes
const describeCache = new LRUCache<string, any>({
max: 50, // Cache up to 50 sObject describes
ttl: 1000 * 60 * 60, // 1 hour TTL (metadata changes are rare)
});
async function cachedDescribe(sObjectType: string) {
const cached = describeCache.get(sObjectType);
if (cached) return cached;
const conn = await getConnection();
const describe = await conn.sobject(sObjectType).describe();
describeCache.set(sObjectType, describe);
return describe;
}
// Cache SOQL query results for frequently-accessed reference data
const queryCache = new LRUCache<string, any>({
max: 100,
ttl: 1000 * 60 * 5, // 5 minute TTL for query results
});
async function cachedQuery<T>(soql: string): Promise<T[]> {
const cached = queryCache.get(soql);
if (cached) return cached;
const conn = await getConnection();
const result = await conn.query<T>(soql);
queryCache.set(soql, result.records);
return result.records;
}
```
### Step 4: Stream Large Result Sets
```typescript
// For large exports (100K+ records), use Bulk API 2.0 query
// Streams results to avoid loading everything into memory
const queryResults = await conn.bulk2.query(
'SELECT Id, Name, Email FROM Contact WHERE CreatedDate >= LAST_YEAR'
);
// Process as async iterator — constant memory usage
let count = 0;
for await (const record of queryResults) {
await processContact(record);
count++;
if (count % 10000 === 0) {
console.log(`Processed ${count} records...`);
}
}
```
### Step 5: Connection Optimization
```typescript
// Reuse connections across requests (singleton pattern)
// jsforce handles keep-alive internally
// Pin API version to avoid version negotiation overhead
const conn = new jsforce.Connection({
loginUrl: process.env.SF_LOGIN_URL,
version: '59.0', // Skip version detection call
maxRequest: 10, // Max concurrent requests
});
```
## Performance Benchmarks
| Operation | Typical Latency | Optimization |
|-----------|----------------|--------------|
| Single SOQL query | 100-300ms | Use selective filters on indexed fields |
| sObject Create (single) | 150-400ms | Batch with Collections (up to 200) |
| Describe call | 200-500ms | Cache for 1 hour |
| Bulk API job creation | 500ms-2s | Use for 10K+ records |
| Composite (25 subrequests) | 500ms-3s | Replaces 25 individual calls |
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| `NON_SELECTIVE_QUERY` | WHERE clause too broad | Add indexed field filters |
| `QUERY_TOO_COMPLICATED` | Too many joins/subqueries | Simplify or split into multiple queries |
| `50,001 row limit` | Too many results | Add LIMIT, or use Bulk API for exports |
| Cache stampede | TTL expired, all threads miss | Use stale-while-revalidate pattern |
## Resources
- [SOQL Performance Best Practices](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_VLSQ.htm)
- [Query Plan Tool](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_query_plan.htm)
- [sObject Collections](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections.htm)
## Next Steps
For cost optimization, see `salesforce-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.