obsidian-rate-limits

21
0
Source

Handle Obsidian file system operations and throttling patterns. Use when processing many files, handling bulk operations, or preventing performance issues from excessive operations. Trigger with phrases like "obsidian rate limit", "obsidian bulk operations", "obsidian file throttling", "obsidian performance limits".

Install

mkdir -p .claude/skills/obsidian-rate-limits && curl -L -o skill.zip "https://mcp.directory/api/skills/download/1205" && unzip -o skill.zip -d .claude/skills/obsidian-rate-limits && rm skill.zip

Installs to .claude/skills/obsidian-rate-limits

About this skill

Obsidian Rate Limits

Overview

Manage file system operations and implement throttling to prevent performance issues in Obsidian plugins.

Prerequisites

  • Understanding of async JavaScript
  • Familiarity with Obsidian vault operations
  • Knowledge of file system performance considerations

Key Concepts

Obsidian Operation Limits

OperationRecommended LimitRisk if Exceeded
File reads100/secondUI freeze
File writes10/secondData corruption risk
Metadata cache reads1000/secondMemory pressure
DOM updates60/secondVisual lag
Event emissions100/secondEvent queue backup

Instructions

Step 1: Implement Async Queue

// src/utils/async-queue.ts
export class AsyncQueue {
  private queue: Array<() => Promise<void>> = [];
  private processing = false;
  private concurrency: number;
  private activeCount = 0;

  constructor(concurrency: number = 1) {
    this.concurrency = concurrency;
  }

  async add<T>(task: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try {
          const result = await task();
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });
      this.process();
    });
  }

  private async process(): Promise<void> {
    if (this.activeCount >= this.concurrency) return;

    const task = this.queue.shift();
    if (!task) return;

    this.activeCount++;
    try {
      await task();
    } finally {
      this.activeCount--;
      this.process();
    }
  }

  get pending(): number {
    return this.queue.length;
  }

  get active(): number {
    return this.activeCount;
  }
}

Step 2: Implement Rate Limiter

// src/utils/rate-limiter.ts
export class RateLimiter {
  private timestamps: number[] = [];
  private limit: number;
  private window: number; // milliseconds

  constructor(limit: number, windowMs: number) {
    this.limit = limit;
    this.window = windowMs;
  }

  async acquire(): Promise<void> {
    const now = Date.now();

    // Remove timestamps outside window
    this.timestamps = this.timestamps.filter(t => now - t < this.window);

    if (this.timestamps.length >= this.limit) {
      // Calculate wait time
      const oldestTimestamp = this.timestamps[0];
      const waitTime = this.window - (now - oldestTimestamp);
      await this.sleep(waitTime);
      return this.acquire();
    }

    this.timestamps.push(now);
  }

  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// Usage:
const writeLimiter = new RateLimiter(10, 1000); // 10 per second

async function safeWriteFile(file: TFile, content: string) {
  await writeLimiter.acquire();
  await this.app.vault.modify(file, content);
}

Step 3: Batch Processing Pattern

// src/utils/batch-processor.ts
export interface BatchOptions {
  batchSize: number;
  delayBetweenBatches: number;
  onProgress?: (processed: number, total: number) => void;
}

export async function processBatches<T, R>(
  items: T[],
  processor: (item: T) => Promise<R>,
  options: BatchOptions
): Promise<R[]> {
  const results: R[] = [];
  const total = items.length;

  for (let i = 0; i < items.length; i += options.batchSize) {
    const batch = items.slice(i, i + options.batchSize);

    // Process batch in parallel
    const batchResults = await Promise.all(
      batch.map(item => processor(item))
    );
    results.push(...batchResults);

    // Report progress
    options.onProgress?.(Math.min(i + options.batchSize, total), total);

    // Delay between batches (except for last batch)
    if (i + options.batchSize < items.length) {
      await sleep(options.delayBetweenBatches);
    }
  }

  return results;
}

function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Usage:
const files = this.app.vault.getMarkdownFiles();

const results = await processBatches(
  files,
  async (file) => {
    const content = await this.app.vault.read(file);
    return { path: file.path, length: content.length };
  },
  {
    batchSize: 50,
    delayBetweenBatches: 100, // 100ms between batches
    onProgress: (processed, total) => {
      console.log(`Processed ${processed}/${total}`);
    },
  }
);

Step 4: Debounced Operations

// src/utils/debounce.ts
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number,
  options: { leading?: boolean; trailing?: boolean; maxWait?: number } = {}
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null;
  let lastCallTime: number | null = null;
  let lastInvokeTime = 0;
  let result: ReturnType<T>;

  const { leading = false, trailing = true, maxWait } = options;

  function invokeFunc(time: number, args: Parameters<T>) {
    lastInvokeTime = time;
    result = func(...args);
    return result;
  }

  return function (...args: Parameters<T>) {
    const time = Date.now();
    const isInvoking = shouldInvoke(time);

    lastCallTime = time;

    if (isInvoking) {
      if (!timeout && leading) {
        return invokeFunc(time, args);
      }
    }

    if (!timeout) {
      timeout = setTimeout(() => {
        timeout = null;
        if (trailing && lastCallTime) {
          invokeFunc(Date.now(), args);
        }
      }, wait);
    }

    // Handle maxWait
    if (maxWait !== undefined) {
      const timeSinceLastInvoke = time - lastInvokeTime;
      if (timeSinceLastInvoke >= maxWait) {
        invokeFunc(time, args);
      }
    }
  };

  function shouldInvoke(time: number): boolean {
    const timeSinceLastCall = lastCallTime ? time - lastCallTime : 0;
    return !lastCallTime || timeSinceLastCall >= wait;
  }
}

// Usage for search input:
const debouncedSearch = debounce(
  async (query: string) => {
    const results = await performSearch(query);
    updateUI(results);
  },
  300,
  { leading: false, trailing: true }
);

// Typing triggers search only after 300ms pause
inputEl.addEventListener('input', (e) => {
  debouncedSearch(e.target.value);
});

Step 5: Throttled Event Handling

// src/utils/throttle.ts
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle = false;
  let lastArgs: Parameters<T> | null = null;

  return function (...args: Parameters<T>) {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
        if (lastArgs) {
          func(...lastArgs);
          lastArgs = null;
        }
      }, limit);
    } else {
      lastArgs = args;
    }
  };
}

// Usage for scroll handling:
const throttledOnScroll = throttle(() => {
  // Update something based on scroll position
  console.log('Scroll position:', window.scrollY);
}, 100);

window.addEventListener('scroll', throttledOnScroll);

Output

  • Async queue for sequential operations
  • Rate limiter for controlled throughput
  • Batch processor for bulk operations
  • Debounce for user input
  • Throttle for frequent events

Error Handling

IssueCauseSolution
UI freezesToo many sync operationsUse async with batching
Data lossWrite conflictsUse async queue
Memory pressureToo many cached readsUse generators
Event stormsNo debouncingDebounce user input
Missed updatesOver-throttlingReduce throttle time

Examples

Progress Modal for Long Operations

async function processAllFiles(app: App, plugin: Plugin) {
  const files = app.vault.getMarkdownFiles();
  const progressModal = new ProgressModal(app);
  progressModal.open();

  try {
    await processBatches(
      files,
      async (file) => {
        // Process file
        return processFile(file);
      },
      {
        batchSize: 20,
        delayBetweenBatches: 50,
        onProgress: (processed, total) => {
          const percent = Math.round((processed / total) * 100);
          progressModal.setProgress(percent, `Processing ${processed}/${total} files`);
        },
      }
    );
    new Notice('Processing complete!');
  } finally {
    progressModal.close();
  }
}

Generator for Large File Sets

async function* iterateFilesWithPause(
  files: TFile[],
  pauseEvery: number = 100,
  pauseMs: number = 10
): AsyncGenerator<TFile> {
  for (let i = 0; i < files.length; i++) {
    yield files[i];

    // Pause periodically to allow UI updates
    if (i > 0 && i % pauseEvery === 0) {
      await new Promise(r => setTimeout(r, pauseMs));
    }
  }
}

// Usage:
for await (const file of iterateFilesWithPause(files)) {
  await processFile(file);
}

Resources

Next Steps

For security practices, see obsidian-security-basics.

More by jeremylongshore

View all →

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

887

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

125

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

334

fuzzing-apis

jeremylongshore

Perform automated fuzz testing on APIs to uncover vulnerabilities, crashes, and unexpected behaviors using diverse malformed inputs.

773

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

263

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

273

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

287790

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

213415

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

212295

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

219234

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

171200

rust-coding-skill

UtakataKyosui

Guides Claude in writing idiomatic, efficient, well-structured Rust code using proper data modeling, traits, impl organization, macros, and build-speed best practices.

166173

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.