Claude
Skills
Sign in
Back

onenote-performance-tuning

Included with Lifetime
$97 forever

Optimize OneNote Graph API performance for large notebooks, image handling, and batch operations. Use when dealing with slow API responses, large notebooks, image uploads, or HTTP 507 errors. Trigger with "onenote performance", "onenote slow", "onenote large notebook", "onenote image upload".

Image & Videosaasonenotemicrosoft

What this skill does

# OneNote — Performance Tuning & Optimization

## Overview

OneNote performance degrades predictably at scale: notebooks with 100+ sections take 3-5 seconds per API call when using `$expand`, pages with embedded images over 4MB fail silently, and sections hitting the page limit return `507 Insufficient Storage`. Image uploads are capped at 25MB per multipart part, and requesting full page content for hundreds of pages without `$select` can exhaust your rate budget in seconds.

This skill provides tested patterns for every performance bottleneck: selective `$expand` and `$select` for minimal payloads, image compression before upload, batch requests via `$batch`, pagination with `$top` to avoid loading thousands of pages, and caching strategies that invalidate on change detection.

Key pain points addressed:

- Full `$expand=sections($expand=pages)` on large notebooks can take 10+ seconds and return multi-MB responses
- Image uploads silently fail when a single multipart part exceeds 25MB — no error, just missing image
- `507 Insufficient Storage` when a section hits its page limit (approximately 5,000 pages)
- Page content retrieval (`GET /pages/{id}/content`) is 5-10x slower than metadata-only requests

## 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 Pillow` (Pillow for image compression)
- Node/TypeScript: `npm install @microsoft/microsoft-graph-client @azure/identity @azure/msal-node sharp` (sharp for image compression)

## Instructions

### Step 1 — Use $select to Minimize Payload Size

Every Graph API call should specify `$select` to return only the fields you need. The default response includes navigation properties, OData metadata, and verbose timestamps that inflate payloads:

```typescript
// BAD — returns ~2KB per page with all metadata
const pages = await client.api("/me/onenote/pages").get();

// GOOD — returns ~200 bytes per page with only needed fields
const pages = await client.api("/me/onenote/pages")
  .select("id,title,lastModifiedDateTime")
  .get();

// For notebooks, avoid expanding everything
// BAD — can take 10+ seconds on large notebooks
const notebooks = await client.api("/me/onenote/notebooks")
  .expand("sections($expand=pages)")
  .get();

// GOOD — get structure first, then drill into sections on demand
const notebooks = await client.api("/me/onenote/notebooks")
  .select("id,displayName,lastModifiedDateTime,sectionsUrl")
  .get();
```

Payload size comparison for a notebook with 50 sections and 500 pages:

| Query | Response Size | Response Time |
|-------|--------------|---------------|
| Full `$expand` | ~800KB | 5-10s |
| `$select` on notebook only | ~2KB | 200ms |
| `$select` + `$top(10)` sections | ~1KB | 150ms |

### Step 2 — Paginate Large Sections

Sections can accumulate thousands of pages. Always use `$top` to limit initial loads:

```typescript
async function* iteratePages(client: any, sectionId: string, pageSize: number = 50) {
  let url: string | null =
    `/me/onenote/sections/${sectionId}/pages?$select=id,title,lastModifiedDateTime&$orderby=lastModifiedDateTime desc&$top=${pageSize}`;

  while (url) {
    const response = await client.api(url).get();
    const pages = response.value ?? [];
    for (const page of pages) {
      yield page;
    }
    // Stop if we got fewer than requested
    if (pages.length < pageSize) break;
    url = response["@odata.nextLink"] ?? null;
  }
}

// Usage — process pages lazily
for await (const page of iteratePages(client, sectionId)) {
  console.log(`Processing: ${page.title}`);
  if (shouldStop(page)) break; // Can bail early
}
```

### Step 3 — Image Upload with Size Validation

OneNote accepts images via multipart form data. Each part is limited to 25MB. Images larger than 4MB in the rendered page can cause performance issues in the client. Always validate and compress before upload:

```typescript
import sharp from "sharp";

interface ImageUploadResult {
  success: boolean;
  originalSize: number;
  compressedSize: number;
  error?: string;
}

async function prepareImageForUpload(
  imageBuffer: Buffer,
  maxSizeBytes: number = 4 * 1024 * 1024, // 4MB target for good page performance
  hardLimit: number = 25 * 1024 * 1024     // 25MB absolute limit per multipart part
): Promise<{ buffer: Buffer; result: ImageUploadResult }> {
  const originalSize = imageBuffer.length;

  if (originalSize > hardLimit) {
    return {
      buffer: imageBuffer,
      result: { success: false, originalSize, compressedSize: originalSize,
        error: `Image exceeds 25MB hard limit (${(originalSize / 1024 / 1024).toFixed(1)}MB)` },
    };
  }

  if (originalSize <= maxSizeBytes) {
    return {
      buffer: imageBuffer,
      result: { success: true, originalSize, compressedSize: originalSize },
    };
  }

  // Progressively compress: reduce quality, then resize
  let compressed = imageBuffer;
  const qualities = [80, 60, 40];

  for (const quality of qualities) {
    compressed = await sharp(imageBuffer)
      .jpeg({ quality, progressive: true })
      .toBuffer();
    if (compressed.length <= maxSizeBytes) break;
  }

  // If still too large, resize
  if (compressed.length > maxSizeBytes) {
    const metadata = await sharp(imageBuffer).metadata();
    const scale = Math.sqrt(maxSizeBytes / compressed.length);
    compressed = await sharp(imageBuffer)
      .resize(Math.round((metadata.width ?? 1920) * scale))
      .jpeg({ quality: 60 })
      .toBuffer();
  }

  return {
    buffer: compressed,
    result: { success: true, originalSize, compressedSize: compressed.length },
  };
}
```

**Supported image formats:** TIFF, PNG, GIF, JPEG, BMP. OneNote does not support WebP or AVIF — convert before uploading.

### Step 4 — Multipart Page Creation with Images

```typescript
async function createPageWithImage(
  client: any,
  sectionId: string,
  title: string,
  htmlBody: string,
  imageName: string,
  imageBuffer: Buffer
): Promise<any> {
  // Validate and compress image
  const { buffer, result } = await prepareImageForUpload(imageBuffer);
  if (!result.success) throw new Error(result.error);

  const boundary = `OneNoteBoundary${Date.now()}`;
  const body = [
    `--${boundary}`,
    'Content-Disposition: form-data; name="Presentation"',
    "Content-Type: text/html",
    "",
    `<!DOCTYPE html><html><head><title>${title}</title></head>`,
    `<body>${htmlBody}<img src="name:${imageName}" alt="${imageName}" /></body></html>`,
    `--${boundary}`,
    `Content-Disposition: form-data; name="${imageName}"`,
    "Content-Type: image/jpeg",
    "",
    buffer.toString("binary"),
    `--${boundary}--`,
  ].join("\r\n");

  return client.api(`/me/onenote/sections/${sectionId}/pages`)
    .header("Content-Type", `multipart/form-data; boundary=${boundary}`)
    .post(body);
}
```

### Step 5 — Batch Requests for Bulk Operations

The `$batch` endpoint processes up to 20 operations per request. This is the single most effective optimization for bulk workloads — it reduces HTTP overhead and counts as one request against rate limits:

```typescript
async function batchGetPageMetadata(
  client: any,
  pageIds: string[]
): Promise<Map<string, any>> {
  const results = new Map<string, any>();
  const BATCH_SIZE = 20;

  for (let i = 0; i < pageIds.length; i += BATCH_SIZE) {
    const chunk = pageIds.slice(i, i + BATCH_SIZE);
    const batchBody = {
      requests: chunk.map((id, idx) => ({
        id: String(idx),
        method: "GET",
        url: `/me/onenote/pages/${id}?$select=id,title,lastModifiedDateTime`,
      })),
    };

    const response = await client.api("/$batch").post(batchBody);

    for (const item of response.responses) {
      if (item.status === 200) {
        results.set(item.body.id, item.body);
      } else if (item.status === 404) {
        // Page was deleted — skip
        console.warn(`Page ${chunk[parseInt(item.

Related in Image & Video