node-performance
Node.js performance optimization patterns
What this skill does
# Node.js Performance Skill
Patterns for optimizing Node.js application performance.
## Memory Management
### Heap Snapshots
```typescript
import v8 from 'v8'
import fs from 'fs'
// Take heap snapshot
function takeHeapSnapshot(filename: string): void {
const snapshotStream = v8.writeHeapSnapshot(filename)
console.log(`Heap snapshot written to ${snapshotStream}`)
}
// Expose via endpoint
app.get('/debug/heap', (req, res) => {
const filename = `/tmp/heap-${Date.now()}.heapsnapshot`
takeHeapSnapshot(filename)
res.download(filename)
})
// Memory usage
function getMemoryUsage(): object {
const usage = process.memoryUsage()
return {
heapUsed: Math.round(usage.heapUsed / 1024 / 1024) + 'MB',
heapTotal: Math.round(usage.heapTotal / 1024 / 1024) + 'MB',
external: Math.round(usage.external / 1024 / 1024) + 'MB',
rss: Math.round(usage.rss / 1024 / 1024) + 'MB',
}
}
```
### Avoiding Memory Leaks
```typescript
// BAD: Growing array
const cache: any[] = []
function addToCache(item: any) {
cache.push(item) // Never cleared
}
// GOOD: LRU cache with limit
import { LRUCache } from 'lru-cache'
const cache = new LRUCache<string, any>({
max: 500, // Max items
maxSize: 50 * 1024 * 1024, // 50MB
sizeCalculation: (value) => JSON.stringify(value).length,
ttl: 1000 * 60 * 5, // 5 minutes
})
// BAD: Event listener leak
class Service {
constructor(emitter: EventEmitter) {
emitter.on('data', this.handleData.bind(this))
// Never removed
}
}
// GOOD: Cleanup listeners
class Service {
private handler: (data: any) => void
constructor(private emitter: EventEmitter) {
this.handler = this.handleData.bind(this)
emitter.on('data', this.handler)
}
destroy() {
this.emitter.off('data', this.handler)
}
}
```
## CPU Optimization
### Worker Threads
```typescript
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads'
import os from 'os'
if (isMainThread) {
// Main thread
const numCPUs = os.cpus().length
async function runTask<T>(data: any): Promise<T> {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: data,
})
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker exited with code ${code}`))
}
})
})
}
// Run CPU-intensive tasks in parallel
const results = await Promise.all(
items.map(item => runTask(item))
)
} else {
// Worker thread
const result = heavyComputation(workerData)
parentPort?.postMessage(result)
}
```
### Worker Pool
```typescript
import { Worker } from 'worker_threads'
import os from 'os'
class WorkerPool {
private workers: Worker[] = []
private freeWorkers: Worker[] = []
private queue: Array<{
data: any
resolve: (value: any) => void
reject: (error: Error) => void
}> = []
constructor(private workerScript: string, size = os.cpus().length) {
for (let i = 0; i < size; i++) {
const worker = new Worker(workerScript)
this.workers.push(worker)
this.freeWorkers.push(worker)
}
}
exec<T>(data: any): Promise<T> {
return new Promise((resolve, reject) => {
const worker = this.freeWorkers.pop()
if (worker) {
this.runWorker(worker, data, resolve, reject)
} else {
this.queue.push({ data, resolve, reject })
}
})
}
private runWorker(
worker: Worker,
data: any,
resolve: (value: any) => void,
reject: (error: Error) => void
) {
const onMessage = (result: any) => {
cleanup()
resolve(result)
this.releaseWorker(worker)
}
const onError = (error: Error) => {
cleanup()
reject(error)
this.releaseWorker(worker)
}
const cleanup = () => {
worker.off('message', onMessage)
worker.off('error', onError)
}
worker.on('message', onMessage)
worker.on('error', onError)
worker.postMessage(data)
}
private releaseWorker(worker: Worker) {
const next = this.queue.shift()
if (next) {
this.runWorker(worker, next.data, next.resolve, next.reject)
} else {
this.freeWorkers.push(worker)
}
}
destroy() {
for (const worker of this.workers) {
worker.terminate()
}
}
}
```
## Caching
### In-Memory Caching
```typescript
import { LRUCache } from 'lru-cache'
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 1000 * 60 * 10, // 10 minutes
})
async function getCachedData<T>(
key: string,
fetcher: () => Promise<T>
): Promise<T> {
const cached = cache.get(key)
if (cached !== undefined) {
return cached as T
}
const data = await fetcher()
cache.set(key, data)
return data
}
// Memoization
function memoize<T extends (...args: any[]) => any>(
fn: T,
keyFn: (...args: Parameters<T>) => string = (...args) => JSON.stringify(args)
): T {
const cache = new Map<string, ReturnType<T>>()
return ((...args: Parameters<T>): ReturnType<T> => {
const key = keyFn(...args)
if (cache.has(key)) {
return cache.get(key)!
}
const result = fn(...args)
cache.set(key, result)
return result
}) as T
}
```
### Redis Caching
```typescript
import Redis from 'ioredis'
const redis = new Redis()
async function cacheWithRedis<T>(
key: string,
fetcher: () => Promise<T>,
ttlSeconds: number = 300
): Promise<T> {
const cached = await redis.get(key)
if (cached) {
return JSON.parse(cached)
}
const data = await fetcher()
await redis.setex(key, ttlSeconds, JSON.stringify(data))
return data
}
// Cache-aside pattern
class CacheAside {
constructor(private redis: Redis) {}
async get<T>(key: string): Promise<T | null> {
const data = await this.redis.get(key)
return data ? JSON.parse(data) : null
}
async set<T>(key: string, value: T, ttl: number): Promise<void> {
await this.redis.setex(key, ttl, JSON.stringify(value))
}
async invalidate(key: string): Promise<void> {
await this.redis.del(key)
}
async getOrFetch<T>(
key: string,
fetcher: () => Promise<T>,
ttl: number
): Promise<T> {
const cached = await this.get<T>(key)
if (cached) return cached
const data = await fetcher()
await this.set(key, data, ttl)
return data
}
}
```
## Connection Pooling
### Database Pool
```typescript
import { Pool } from 'pg'
const pool = new Pool({
host: 'localhost',
database: 'mydb',
max: 20, // Max connections
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
})
// Measure pool usage
setInterval(() => {
console.log({
total: pool.totalCount,
idle: pool.idleCount,
waiting: pool.waitingCount,
})
}, 10000)
// Use pool
const result = await pool.query('SELECT * FROM users')
```
### HTTP Agent Pool
```typescript
import http from 'http'
import https from 'https'
const httpAgent = new http.Agent({
keepAlive: true,
maxSockets: 100,
maxFreeSockets: 10,
timeout: 60000,
})
const httpsAgent = new https.Agent({
keepAlive: true,
maxSockets: 100,
})
// Use with fetch
const response = await fetch(url, {
agent: url.startsWith('https') ? httpsAgent : httpAgent,
})
```
## Profiling
### CPU Profiling
```typescript
import { Session } from 'inspector'
import fs from 'fs'
async function profileCPU(
fn: () => Promise<void>,
outputFile: string
): Promise<void> {
const session = new Session()
session.connect()
await new Promise<void>((resolve) => {
session.post('Profiler.enable', () => {
session.post('Profiler.start', () => resolve())
})
})
await fn()
const profile = await new Promise<object>((resolve) => {
session.post('Profiler.stop', (err, { profile }) => {
resolve(profile)
})
})
fs.writeFileSync(outputFile, JSON.stringify(profile))
session.disconnect()
}
```
### Benchmarking
```typescript
function benchmark(nameRelated 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.