onenote-rate-limits
Implement proper rate limit handling for OneNote Graph API with queue-based throttling. Use when building high-throughput OneNote integrations or debugging 429 errors. Trigger with "onenote rate limit", "onenote 429", "onenote throttling", "graph api throttle".
What this skill does
# OneNote — Rate Limit Handling & Request Throttling
## Overview
Microsoft Graph rate limits OneNote at **600 requests per 60 seconds per user** and **10,000 requests per 10 minutes per app/tenant**. When you exceed either limit, the API returns `429 Too Many Requests` with a `Retry-After` header specifying how many seconds to wait. Most implementations either ignore this header entirely (retrying immediately, making things worse) or use a fixed backoff that wastes capacity.
This skill implements a token bucket rate limiter, queue-based request throttling, and proper `Retry-After` header parsing. For multi-user apps, it tracks per-user and per-tenant budgets independently.
Key pain points addressed:
- The `Retry-After` header value is in seconds (not milliseconds) — many implementations parse this wrong
- The per-user limit (600/60s) is separate from the per-tenant limit (10,000/10min) — you can hit one without the other
- Batch requests (`$batch`) count as one request toward the limit, regardless of how many operations are inside
- After a 429, subsequent requests to ANY OneNote endpoint are throttled — not just the endpoint that triggered it
## Prerequisites
- Azure app registration with delegated permissions: `Notes.ReadWrite`
- App-only auth deprecated March 31, 2025 — use delegated auth only
- Python: `pip install msgraph-sdk azure-identity`
- Node/TypeScript: `npm install @microsoft/microsoft-graph-client @azure/identity @azure/msal-node`
- Optional: `npm install p-queue` for production queue management
## Instructions
### Step 1 — Understand the Rate Limit Structure
| Limit | Scope | Window | Threshold |
|-------|-------|--------|-----------|
| Per-user | Single user's delegated token | 60 seconds (rolling) | 600 requests |
| Per-tenant | All users + all apps in the tenant | 10 minutes (rolling) | 10,000 requests |
When either limit is hit:
- Response status: `429 Too Many Requests`
- Response header: `Retry-After: <seconds>` (integer, not milliseconds)
- All subsequent OneNote requests for that scope are blocked until the window resets
- Non-OneNote Graph endpoints (Outlook, OneDrive) are **not** affected
### Step 2 — Token Bucket Rate Limiter (TypeScript)
A token bucket preemptively throttles requests to stay below the limit, avoiding 429s entirely:
```typescript
class TokenBucket {
private tokens: number;
private lastRefill: number;
private readonly maxTokens: number;
private readonly refillRate: number; // tokens per millisecond
constructor(maxTokens: number, refillWindowMs: number) {
this.maxTokens = maxTokens;
this.tokens = maxTokens;
this.lastRefill = Date.now();
this.refillRate = maxTokens / refillWindowMs;
}
private refill(): void {
const now = Date.now();
const elapsed = now - this.lastRefill;
this.tokens = Math.min(this.maxTokens, this.tokens + elapsed * this.refillRate);
this.lastRefill = now;
}
async acquire(): Promise<void> {
this.refill();
if (this.tokens >= 1) {
this.tokens -= 1;
return;
}
// Wait until a token is available
const waitMs = Math.ceil((1 - this.tokens) / this.refillRate);
await new Promise((resolve) => setTimeout(resolve, waitMs));
this.tokens -= 1;
}
get available(): number {
this.refill();
return Math.floor(this.tokens);
}
}
// Per-user bucket: 600 requests per 60 seconds
const userBucket = new TokenBucket(600, 60_000);
// Use with a safety margin (80% of limit)
const safeUserBucket = new TokenBucket(480, 60_000);
```
### Step 3 — Queue-Based Request Throttling
Wrap all OneNote API calls through a throttled queue that respects both the token bucket and `Retry-After` headers:
```typescript
import { Client } from "@microsoft/microsoft-graph-client";
class ThrottledOneNoteClient {
private bucket: TokenBucket;
private queue: Array<{
resolve: (value: any) => void;
reject: (error: any) => void;
fn: () => Promise<any>;
}> = [];
private processing = false;
private retryAfterUntil: number = 0; // Timestamp when retry-after expires
constructor(
private client: Client,
maxRequestsPerMinute: number = 480 // 80% safety margin
) {
this.bucket = new TokenBucket(maxRequestsPerMinute, 60_000);
}
async request<T>(fn: (client: Client) => Promise<T>): Promise<T> {
return new Promise((resolve, reject) => {
this.queue.push({ resolve, reject, fn: () => fn(this.client) });
this.processQueue();
});
}
private async processQueue(): Promise<void> {
if (this.processing) return;
this.processing = true;
while (this.queue.length > 0) {
// Respect Retry-After if we've been throttled
const now = Date.now();
if (this.retryAfterUntil > now) {
const waitMs = this.retryAfterUntil - now;
console.warn(`Rate limited — waiting ${Math.ceil(waitMs / 1000)}s`);
await new Promise((r) => setTimeout(r, waitMs));
}
await this.bucket.acquire();
const item = this.queue.shift()!;
try {
const result = await item.fn();
item.resolve(result);
} catch (err: any) {
if (err.statusCode === 429) {
const retryAfter = parseInt(err.headers?.["retry-after"] ?? "30", 10);
this.retryAfterUntil = Date.now() + retryAfter * 1000;
// Re-queue the failed request
this.queue.unshift(item);
console.warn(`429 received — Retry-After: ${retryAfter}s`);
} else {
item.reject(err);
}
}
}
this.processing = false;
}
}
// Usage
const throttled = new ThrottledOneNoteClient(client);
const notebooks = await throttled.request((c) =>
c.api("/me/onenote/notebooks").get()
);
```
### Step 4 — Per-User Tracking for Multi-User Apps
Multi-user apps must track rate limits per user, not globally:
```typescript
class MultiUserRateLimiter {
private userBuckets: Map<string, TokenBucket> = new Map();
private tenantBucket: TokenBucket;
constructor() {
// Tenant-wide: 10,000 per 10 minutes
this.tenantBucket = new TokenBucket(8_000, 600_000); // 80% safety margin
}
async acquire(userId: string): Promise<void> {
// Get or create per-user bucket
if (!this.userBuckets.has(userId)) {
this.userBuckets.set(userId, new TokenBucket(480, 60_000));
}
const userBucket = this.userBuckets.get(userId)!;
// Must acquire from BOTH buckets
await userBucket.acquire();
await this.tenantBucket.acquire();
}
getStatus(userId: string): { userRemaining: number; tenantRemaining: number } {
const userBucket = this.userBuckets.get(userId);
return {
userRemaining: userBucket?.available ?? 480,
tenantRemaining: this.tenantBucket.available,
};
}
}
```
### Step 5 — Exponential Backoff with Jitter
For 429 responses without a `Retry-After` header (rare but possible), use exponential backoff with jitter:
```typescript
async function withBackoff<T>(
fn: () => Promise<T>,
maxRetries: number = 5
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (err: any) {
if (err.statusCode !== 429 || attempt === maxRetries) throw err;
const retryAfter = err.headers?.["retry-after"];
let delayMs: number;
if (retryAfter) {
// Prefer server-specified delay (in seconds)
delayMs = parseInt(retryAfter, 10) * 1000;
} else {
// Exponential backoff: 1s, 2s, 4s, 8s, 16s + jitter
const base = Math.pow(2, attempt) * 1000;
const jitter = Math.random() * 1000;
delayMs = base + jitter;
}
console.warn(`Retry ${attempt + 1}/${maxRetries} in ${Math.ceil(delayMs / 1000)}s`);
await new Promise((r) => setTimeout(r, delayMs));
}
}
throw new Error("Unreachable");
}
// Usage
const pages = await withBackoff(() =>
client.api("/me/onenote/pages").top(50).get()
);
```
### Step 6 — Batch Requests to Reduce Call Count
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.