Claude
Skills
Sign in
Back

onenote-cost-tuning

Included with Lifetime
$97 forever

Optimize costs and API usage for OneNote Graph API integrations with caching and batching strategies. Use when reducing API call volume, planning capacity, or evaluating OneNote integration costs. Trigger with "onenote costs", "onenote api usage", "onenote optimization", "graph api billing onenote".

Backend & APIssaasonenotemicrosoft

What this skill does

# OneNote Cost Tuning

## Overview

OneNote Graph API calls have no per-request cost — they are included in every Microsoft 365 E3/E5/Business license. However, rate limits create an effective ceiling that functions like a cost constraint: 600 requests per user per 60 seconds and 10,000 requests per app per 10 minutes at the tenant level. Exceeding these limits returns 429 errors with Retry-After headers, degrading user experience the same way budget overruns degrade service. This skill covers the practical optimization strategies that keep you well under those ceilings: metadata caching, JSON batch requests, delta sync, payload minimization with `$select`/`$expand`, and content deduplication. A naive integration that polls every user's notebooks every minute burns through the tenant limit in under 10 minutes. An optimized one handles thousands of users within the same budget.

## Prerequisites

- Microsoft 365 license (E3/E5/Business) — OneNote API is included, no additional billing
- Azure AD app registration with delegated permissions
- Python: `pip install msgraph-sdk azure-identity` or Node: `npm install @microsoft/microsoft-graph-client @azure/identity`
- Understanding of HTTP caching headers (ETag, If-None-Match)

## Instructions

### Licensing Model and True Cost

| Component | Cost |
|-----------|------|
| OneNote API calls | Included in M365 license (no per-call charge) |
| Rate limit: per user | 600 requests / 60 seconds |
| Rate limit: per tenant | 10,000 requests / 10 minutes |
| Retry-After penalty | Blocked for N seconds (header value) |
| Graph metered billing | Optional; extends limits for high-volume apps |

**The real cost is operational:** every 429 response adds latency, retry logic consumes compute, and throttled users see failures. Optimization is about reliability, not billing.

### Strategy 1: Cache Metadata Aggressively

Notebook and section metadata changes rarely (names, IDs, hierarchy). Cache it locally and refresh on a schedule, not per-request:

```typescript
interface CachedMetadata {
  notebooks: any[];
  sections: Map<string, any[]>;  // notebookId -> sections
  fetchedAt: number;
  ttlMs: number;
}

class MetadataCache {
  private cache: CachedMetadata = {
    notebooks: [],
    sections: new Map(),
    fetchedAt: 0,
    ttlMs: 15 * 60 * 1000,  // 15 minutes — notebooks/sections rarely change
  };

  isStale(): boolean {
    return Date.now() - this.cache.fetchedAt > this.cache.ttlMs;
  }

  async getNotebooks(client: any): Promise<any[]> {
    if (!this.isStale() && this.cache.notebooks.length > 0) {
      return this.cache.notebooks;  // 0 API calls
    }
    const response = await client.api("/me/onenote/notebooks")
      .select("id,displayName,lastModifiedDateTime")
      .get();
    this.cache.notebooks = response.value;
    this.cache.fetchedAt = Date.now();
    return this.cache.notebooks;  // 1 API call
  }

  async getSections(client: any, notebookId: string): Promise<any[]> {
    if (!this.isStale() && this.cache.sections.has(notebookId)) {
      return this.cache.sections.get(notebookId)!;
    }
    const response = await client
      .api(`/me/onenote/notebooks/${notebookId}/sections`)
      .select("id,displayName")
      .get();
    this.cache.sections.set(notebookId, response.value);
    return response.value;
  }

  invalidate(): void {
    this.cache.fetchedAt = 0;
  }
}
```

**Savings:** A typical app listing notebooks 100 times/hour drops from 100 calls to 4 calls (one refresh per 15-minute TTL window).

### Strategy 2: JSON Batch Requests

The `$batch` endpoint combines up to 20 requests into a single HTTP call, reducing call count by up to 20x:

```python
import httpx

async def batch_get_sections(access_token: str, notebook_ids: list[str]) -> dict:
    """Fetch sections for multiple notebooks in a single HTTP call."""
    requests = []
    for i, nb_id in enumerate(notebook_ids[:20]):  # Max 20 per batch
        requests.append({
            "id": str(i),
            "method": "GET",
            "url": f"/me/onenote/notebooks/{nb_id}/sections?$select=id,displayName",
        })

    async with httpx.AsyncClient() as http:
        response = await http.post(
            "https://graph.microsoft.com/v1.0/$batch",
            headers={
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json",
            },
            json={"requests": requests},
        )
        batch_result = response.json()

    # Map responses back to notebook IDs
    result = {}
    for resp in batch_result["responses"]:
        idx = int(resp["id"])
        nb_id = notebook_ids[idx]
        if resp["status"] == 200:
            result[nb_id] = resp["body"]["value"]
        else:
            result[nb_id] = []  # Handle individual failures gracefully
    return result
```

**Savings:** Fetching sections for 20 notebooks: 20 calls becomes 1 call. For 100 notebooks, 100 calls becomes 5 calls.

### Strategy 3: Delta Sync Instead of Full Sync

Delta queries return only changes since your last sync, replacing full-list operations that grow linearly with data size:

```typescript
class DeltaSyncer {
  private deltaLinks: Map<string, string> = new Map();

  async syncPages(client: any, sectionId: string): Promise<{
    added: any[];
    modified: any[];
    deleted: string[];
  }> {
    const deltaLink = this.deltaLinks.get(sectionId);
    const url = deltaLink || `/me/onenote/sections/${sectionId}/pages/delta`;

    const response = await client.api(url).get();
    const result = { added: [] as any[], modified: [] as any[], deleted: [] as string[] };

    for (const page of response.value || []) {
      if (page["@removed"]) {
        result.deleted.push(page.id);
      } else if (deltaLink) {
        result.modified.push(page);
      } else {
        result.added.push(page);
      }
    }

    // Store the delta link for next sync
    if (response["@odata.deltaLink"]) {
      this.deltaLinks.set(sectionId, response["@odata.deltaLink"]);
    }

    return result;
  }
}
```

**Savings:** A section with 500 pages that changes 3 pages/hour: full sync = 500+ items per response, delta sync = 3 items. Call count may be same (1), but payload size drops 99%.

### Strategy 4: Payload Minimization with $select and $expand

Every field you do not request is bandwidth you save and parsing you skip:

```bash
# BAD: Returns all fields including content URLs, permissions, links (2-5 KB per page)
GET /me/onenote/sections/{id}/pages

# GOOD: Returns only what you need (200-300 bytes per page)
GET /me/onenote/sections/{id}/pages?$select=id,title,createdDateTime,lastModifiedDateTime&$top=50&$orderby=lastModifiedDateTime desc
```

Use `$expand` to eliminate follow-up calls:

```text
# Without $expand: 1 call for notebooks + N calls for sections = N+1 calls
GET /me/onenote/notebooks
GET /me/onenote/notebooks/{id1}/sections
GET /me/onenote/notebooks/{id2}/sections

# With $expand: 1 call total
GET /me/onenote/notebooks?$expand=sections($select=id,displayName)&$select=id,displayName
```

### Strategy 5: Content Deduplication

Hash page content before writing to avoid duplicate POST calls:

```python
import hashlib

def content_hash(html_body: str) -> str:
    """Generate a stable hash of page content for dedup."""
    return hashlib.sha256(html_body.encode("utf-8")).hexdigest()

class DeduplicatedWriter:
    def __init__(self):
        self.written_hashes: dict[str, str] = {}  # hash -> page_id

    async def write_page(self, client, section_id: str, title: str, html_body: str):
        h = content_hash(html_body)
        if h in self.written_hashes:
            return self.written_hashes[h]  # Skip duplicate write

        full_html = (
            f"<html><head><title>{title}</title></head>"
            f"<body>{html_body}</body></html>"
        )
        page = await client.me.onenote.sections.by_onenote_section_id(
            section_id
        ).pages.post(content=full_html.encode())
       

Related in Backend & APIs