notion-performance-tuning
Optimize Notion API performance with caching, batching, parallel requests, and incremental sync. Use when experiencing slow API responses, implementing caching strategies, reducing API call volume, or tuning request patterns for Notion integrations. Trigger with phrases like "notion performance", "optimize notion api", "notion latency", "notion caching", "notion slow", "notion batch requests", "notion incremental sync", "notion reduce api calls".
What this skill does
# Notion Performance Tuning
## Overview
Optimize Notion API performance by minimizing API calls, caching responses with TTL-based invalidation, batching block appends, parallelizing requests within rate limits, selecting only needed properties, and implementing incremental sync patterns. Target latency benchmarks: Database Query p50=150ms, Page Create p50=200ms, Search p50=300ms.
## Prerequisites
- `@notionhq/client` installed (`npm install @notionhq/client`)
- `p-queue` for rate-limited parallelism (`npm install p-queue`)
- `lru-cache` for TTL-based caching (`npm install lru-cache`)
- Understanding of your access patterns (read-heavy vs write-heavy)
- Optional: Redis or `ioredis` for distributed caching across instances
## Instructions
### Step 1: Minimize API Calls and Reduce Payload
Avoid N+1 query patterns. Use `page_size: 100` (the maximum) to reduce pagination requests. Select only the properties you need in database queries to shrink response payloads.
```typescript
import { Client } from '@notionhq/client';
const notion = new Client({ auth: process.env.NOTION_TOKEN });
// BAD: N+1 pattern — fetching content for every page individually
async function fetchAllBad(dbId: string) {
const pages = await notion.databases.query({ database_id: dbId });
for (const page of pages.results) {
// Each iteration is a separate API call — O(n) requests
const content = await notion.blocks.children.list({ block_id: page.id });
}
}
// GOOD: Use filter_properties to select only needed fields
async function fetchAllGood(dbId: string) {
const pages = await notion.databases.query({
database_id: dbId,
page_size: 100, // Maximum — reduces total pagination requests
filter: {
property: 'Status',
select: { equals: 'Active' },
},
// Select only the properties you need by property ID
// Find IDs via: notion.databases.retrieve({ database_id: dbId })
filter_properties: ['title', 'Status', 'Priority'],
});
// Properties are already in the response — no extra retrieve calls
for (const page of pages.results) {
if ('properties' in page) {
const title = page.properties.Name?.type === 'title'
? page.properties.Name.title.map(t => t.plain_text).join('')
: '';
const status = page.properties.Status?.type === 'select'
? page.properties.Status.select?.name
: undefined;
// Use properties directly — zero additional API calls
}
}
return pages;
}
// Batch block appends — up to 100 blocks per request
async function appendBlocks(pageId: string, items: string[]) {
const blocks = items.map(item => ({
object: 'block' as const,
type: 'paragraph' as const,
paragraph: {
rich_text: [{ type: 'text' as const, text: { content: item } }],
},
}));
// BAD: one call per block = N API calls
// for (const block of blocks) {
// await notion.blocks.children.append({ block_id: pageId, children: [block] });
// }
// GOOD: batch in chunks of 100 (API maximum)
for (let i = 0; i < blocks.length; i += 100) {
await notion.blocks.children.append({
block_id: pageId,
children: blocks.slice(i, i + 100),
});
}
}
// Avoid recursive block fetching unless you actually need nested content
async function getTopLevelBlocks(pageId: string) {
const blocks = await notion.blocks.children.list({
block_id: pageId,
page_size: 100,
});
// Only recurse into blocks that have children AND you need them
const expandable = blocks.results.filter(
(b) => 'has_children' in b && b.has_children && needsExpansion(b)
);
// Fetch children only for blocks that matter
return { topLevel: blocks.results, expandable };
}
function needsExpansion(block: any): boolean {
// Only expand toggles and nested content — skip paragraphs, headings, etc.
return ['toggle', 'child_page', 'child_database', 'column_list'].includes(block.type);
}
```
### Step 2: Cache Responses with TTL-Based Invalidation
Implement in-memory caching with LRU eviction and TTL expiration. Invalidate cache entries on writes to maintain consistency.
```typescript
import { LRUCache } from 'lru-cache';
import { Client } from '@notionhq/client';
const notion = new Client({ auth: process.env.NOTION_TOKEN });
// Tiered TTL cache — different durations for different data volatility
const cache = new LRUCache<string, any>({
max: 1000, // max entries
ttl: 60_000, // default 1-minute TTL
updateAgeOnGet: false, // don't extend TTL on reads (ensures freshness)
allowStale: false, // never return expired entries
});
// Cache configuration per operation type
const TTL = {
DATABASE_SCHEMA: 300_000, // 5 min — schemas rarely change
DATABASE_QUERY: 60_000, // 1 min — data changes frequently
PAGE_RETRIEVE: 120_000, // 2 min — pages change occasionally
SEARCH: 30_000, // 30s — search results are volatile
BLOCK_CHILDREN: 60_000, // 1 min — content updates moderately
} as const;
async function cachedDatabaseQuery(dbId: string, filter?: any, sorts?: any) {
const cacheKey = `db:${dbId}:${JSON.stringify({ filter, sorts })}`;
const cached = cache.get(cacheKey);
if (cached) return cached;
const allPages: any[] = [];
let cursor: string | undefined;
do {
const response = await notion.databases.query({
database_id: dbId,
filter,
sorts,
page_size: 100,
start_cursor: cursor,
});
allPages.push(...response.results);
cursor = response.has_more ? response.next_cursor ?? undefined : undefined;
} while (cursor);
const result = { results: allPages, count: allPages.length };
cache.set(cacheKey, result, { ttl: TTL.DATABASE_QUERY });
return result;
}
async function cachedPageRetrieve(pageId: string) {
const cacheKey = `page:${pageId}`;
const cached = cache.get(cacheKey);
if (cached) return cached;
const page = await notion.pages.retrieve({ page_id: pageId });
cache.set(cacheKey, page, { ttl: TTL.PAGE_RETRIEVE });
return page;
}
// Invalidate on writes — consistency over speed
async function createPageInvalidating(dbId: string, properties: any) {
const page = await notion.pages.create({
parent: { database_id: dbId },
properties,
});
// Invalidate all cached queries for this database
for (const key of cache.keys()) {
if (key.startsWith(`db:${dbId}:`)) cache.delete(key);
}
return page;
}
async function updatePageInvalidating(pageId: string, properties: any) {
const page = await notion.pages.update({ page_id: pageId, properties });
// Invalidate specific page cache and parent database queries
cache.delete(`page:${pageId}`);
// If you know the parent DB, invalidate its queries too:
// for (const key of cache.keys()) {
// if (key.startsWith(`db:${parentDbId}:`)) cache.delete(key);
// }
return page;
}
// Cache stats for monitoring
function getCacheStats() {
return {
size: cache.size,
maxSize: cache.max,
hitRate: cache.size > 0 ? 'check cache.get return values' : 'empty',
};
}
```
### Step 3: Parallel Requests with Rate-Limited Queue and Latency Monitoring
See [parallel requests and latency monitoring](references/parallel-requests-and-monitoring.md) for `p-queue` rate-limited parallelism, latency tracking with p50/p95 benchmarks, incremental sync, and memory-efficient streaming via async generators.
## Output
- Reduced API call count through property selection, filtering, and batched block appends
- TTL-based caching with write-through invalidation for data consistency
- Parallel requests within Notion's 3 req/sec rate limit using `p-queue`
- Incremental sync fetching only changed pages since last sync timestamp
- Latency monitoring with p50/p95 tracking against target benchmarks
- Memory-efficient streaming for large datasets via async generators
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Stale cache data | TTL too long for volatile data | Use shorter TTLRelated 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.