Оптимизация использования Notion API для снижения нагрузки на лимиты.

Звёзды2 926
Авторjeremylongshore

Установка

SKILL.md

Notion Cost Tuning

Overview

The Notion API is free with every workspace plan — there is no per-call pricing. The real "cost" is the 3 requests/second rate limit (per integration token) plus the engineering time wasted on inefficient patterns. Apply the six strategies below to reduce request volume by 80-95%.

Notion workspace pricing (for context — API access is included at every tier):

PlanPriceAPI AccessRate Limit
Free$0Full API3 req/sec
Plus$12/user/moFull API3 req/sec
Business$28/user/moFull API3 req/sec
EnterpriseCustomFull API3 req/sec

The rate limit is identical across all plans. Optimization is about staying within 3 req/sec, not reducing a bill.

Prerequisites

  • @notionhq/client v2.x installed (npm install @notionhq/client)
  • Integration token from notion.so/my-integrations
  • Token shared with target pages/databases via the Connections menu in Notion
  • For queue patterns: p-queue v8+ (npm install p-queue)
  • For caching: node-cache or lru-cache (npm install lru-cache)

Authentication

Every technique here uses the same auth as any Notion integration: a single bearer token passed to the client constructor. Store it in an environment variable (NOTION_TOKEN) — never hardcode it — and share it with each target page/database through the Connections menu. One token = one 3 req/sec budget; provision a separate integration token per service when you need independent budgets.

const notion = new Client({ auth: process.env.NOTION_TOKEN });

Instructions

Work the three steps in order. Each links to the full, copy-paste-ready code in references/implementation.md; the essentials are inlined below so you can follow the flow from here.

Step 1: Audit current request volume

Measure before optimizing. Wrap every Notion call in a tracker that records method, endpoint, timestamp, and duration, then print a per-minute report to find the operations eating > 50% of your budget (usually polling loops, redundant retrieves, and full-table scans).

async function tracked<T>(method: string, fn: () => Promise<T>): Promise<T> {
  const start = Date.now();
  try {
    return await fn();
  } finally {
    requestLog.push({ method, timestamp: start, durationMs: Date.now() - start });
  }
}

Full tracker + auditReport(): references/implementation.md, § Step 1.

Step 2: Eliminate redundant reads and shrink payloads

Three patterns cut reads immediately: (A) stop calling pages.retrieve on pages you already got from databases.query — the properties are already there; (B) pass filter_properties (property IDs, not names) to shrink responses 60-90%; (C) filter on last_edited_time to fetch only what changed since the last sync instead of re-scanning the whole database.

// Redundant: query already returned every property — skip the retrieve
const { results } = await notion.databases.query({ database_id: dbId });
for (const page of results) processPage(page); // 1 request total, not 1 + N

All three patterns with runnable code: references/implementation.md, § Step 2.

Step 3: Cache, batch, and replace polling

Cache read-heavy data with a TTL'd LRU; throttle writes through a p-queue sized to the 3 req/sec limit; batch up to 100 blocks per blocks.children.append; and replace polling loops with webhooks (a 10-second poll costs 360 requests/hour per database — webhooks cost zero).

// Rate-limited write queue — never exceeds 3 req/sec
const queue = new PQueue({ concurrency: 3, interval: 1000, intervalCap: 3 });

Caching, batching, and the webhook handler: references/implementation.md, § Step 3.

Output

After applying these optimizations:

  • Audit report showing request volume baseline and hotspots
  • Redundant reads eliminated — no duplicate pages.retrieve after databases.query
  • Payload sizes reduced 60-90% via filter_properties
  • Incremental sync via last_edited_time filter replacing full-table scans
  • Cache layer with TTL-based invalidation for reads
  • Write throughput maximized via queue-based throttling and block batching
  • Polling eliminated where webhooks are available (360 req/hr per database saved)

Typical impact: integrations drop from 500+ requests/hour to under 200 requests/hour (80-95% reduction), staying well within the 3 req/sec limit even with multiple databases.

Error Handling

IssueCauseSolution
429 Too Many Requests despite optimizationShared token across multiple servicesUse separate integration tokens per service; each gets its own 3 req/sec budget
Stale cached data causing bugsCache TTL too long for the use caseShorten TTL to 30-60s for volatile data, or use webhook-based cache invalidation
Webhook not triggeringIntegration not connected to the page/databaseShare via Connections menu in Notion; verify webhook URL is publicly accessible
filter_properties returning empty resultsUsing property names instead of IDsRun databases.retrieve to get property IDs (short strings like abc1), not display names
Incremental sync missing updatesClock skew between client and Notion serverSubtract 5-second buffer from lastSync timestamp to create overlap window
blocks.children.append failing with 400More than 100 children in single callChunk arrays into groups of 100 before appending

Examples

Two complete worked examples live in references/examples.md:

  • Request Reduction Calculator — estimate before/after request volume and rate-limit headroom for your own database count, page count, and poll interval before you commit to changes.
  • Full Optimization Wrapper — a drop-in createOptimizedClient(token) that bundles caching, request tracking, and a rate-limited write queue into one client.

Skeleton of the wrapper (full body in the reference):

export function createOptimizedClient(token: string) {
  const notion = new Client({ auth: token });
  const cache = new LRUCache<string, any>({ max: 1000, ttl: 5 * 60 * 1000 });
  const writeQueue = new PQueue({ concurrency: 3, interval: 1000, intervalCap: 3 });
  // getPage / queryDatabase / createPage / invalidate / stats — see references/examples.md
}

Resources

  • Notion API Rate Limits — 3 req/sec per token, Retry-After header on 429
  • Database Query Filter — push filtering server-side
  • Filter Properties Parameter — reduce response payload size
  • Notion Webhooks — event-driven updates replacing polling
  • Block Children Append — batch up to 100 blocks per call
  • Notion Pricing — API included at all tiers, no per-call charges
  • references/implementation.md — full three-step walkthrough with complete code
  • references/examples.md — request calculator and drop-in optimized client

Next Steps

For rate-limit retry patterns, see notion-rate-limits. For query and search patterns, see notion-search-retrieve. For overall architecture guidance, see notion-reference-architecture.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: notion-cost-tuning](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-notion-cost-tuning)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Harness Optimizeraffaan-m · Анализирует и улучшает конфигурацию локального агентного харнесса по надёжности и цене.
225 587 ★
ruflo-cost-trackerruvnet · Отслеживание расхода токенов, атрибуция затрат на модели по агентам, оповещения о бюджете…
240 комп.
ruflo-metaharnessruvnet · Интеграция MetaHarness: доступ к score/genome/mint/mcp-scan/threat-model через навыки…
240 комп.
ruflo-ruvllmruvnet · Локальный инференс RuVLLM с форматированием чата, дообучением MicroLoRA и адаптацией SONA.
240 комп.
aws-startup-advisoranthropics · Персонализированные рекомендации по архитектуре, затратам, безопасности и миграции для…
100 комп.
azureanthropics · Превращает Claude в эксперта по Azure. Плагин объединяет Azure MCP-сервер и…
100 комп.
azure-cosmos-db-assistantanthropics · Экспертный помощник по Azure Cosmos DB — моделирование данных, оптимизация запросов…
100 комп.
clickhouseanthropics · Подключение Claude к базам данных ClickHouse Cloud. Просмотр организаций, сервисов, баз…
100 комп.
deploy-on-awsanthropics · Развёртывание приложений в AWS с рекомендациями по архитектуре, оценкой затрат и…
100 комп.
migration-to-awsanthropics · Планирование миграции с Google Cloud Platform (и AI-нагрузок OpenAI/Gemini) на AWS…
100 комп.

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8