linear-rate-limits

0
0
Source

Handle Linear API rate limiting and quotas effectively. Use when dealing with rate limit errors, implementing throttling, or optimizing API usage patterns. Trigger with phrases like "linear rate limit", "linear throttling", "linear API quota", "linear 429 error", "linear request limits".

Install

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

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

About this skill

Linear Rate Limits

Overview

Linear uses the leaky bucket algorithm with two rate limiting dimensions. Understanding both is critical for reliable integrations:

BudgetLimitRefill Rate
Requests5,000/hour per API key~83/min constant refill
Complexity250,000 points/hour~4,167/min constant refill
Max single query10,000 pointsHard reject if exceeded

Complexity scoring: Each property = 0.1 pt, each object = 1 pt, connections multiply children by first arg (default 50), then round up.

Prerequisites

  • @linear/sdk installed
  • Understanding of HTTP response headers
  • Familiarity with async/await patterns

Instructions

Step 1: Read Rate Limit Headers

Linear returns rate limit info on every response.

const response = await fetch("https://api.linear.app/graphql", {
  method: "POST",
  headers: {
    Authorization: process.env.LINEAR_API_KEY!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ query: "{ viewer { id } }" }),
});

// Key headers
const headers = {
  requestsRemaining: response.headers.get("x-ratelimit-requests-remaining"),
  requestsLimit: response.headers.get("x-ratelimit-requests-limit"),
  requestsReset: response.headers.get("x-ratelimit-requests-reset"),
  complexityRemaining: response.headers.get("x-ratelimit-complexity-remaining"),
  complexityLimit: response.headers.get("x-ratelimit-complexity-limit"),
  queryComplexity: response.headers.get("x-complexity"),
};

console.log(`Requests: ${headers.requestsRemaining}/${headers.requestsLimit}`);
console.log(`Complexity: ${headers.complexityRemaining}/${headers.complexityLimit}`);
console.log(`This query cost: ${headers.queryComplexity} points`);

Step 2: Exponential Backoff with Jitter

import { LinearClient } from "@linear/sdk";

class RateLimitedClient {
  private client: LinearClient;

  constructor(apiKey: string) {
    this.client = new LinearClient({ apiKey });
  }

  async withRetry<T>(fn: () => Promise<T>, maxRetries = 5): Promise<T> {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        return await fn();
      } catch (error: any) {
        const isRateLimited = error.status === 429 ||
          error.message?.includes("rate") ||
          error.type === "ratelimited";

        if (!isRateLimited || attempt === maxRetries - 1) throw error;

        // Exponential backoff: 1s, 2s, 4s, 8s, 16s + jitter
        const delay = 1000 * Math.pow(2, attempt) + Math.random() * 500;
        console.warn(`Rate limited (attempt ${attempt + 1}/${maxRetries}), waiting ${Math.round(delay)}ms`);
        await new Promise(r => setTimeout(r, delay));
      }
    }
    throw new Error("Unreachable");
  }

  get sdk() { return this.client; }
}

Step 3: Request Queue with Token Bucket

Prevent bursts by spacing requests evenly.

class RequestQueue {
  private queue: Array<{ fn: () => Promise<any>; resolve: Function; reject: Function }> = [];
  private processing = false;
  private intervalMs: number;

  constructor(requestsPerSecond = 10) {
    this.intervalMs = 1000 / requestsPerSecond;
  }

  async enqueue<T>(fn: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push({ fn, resolve, reject });
      if (!this.processing) this.processQueue();
    });
  }

  private async processQueue() {
    this.processing = true;
    while (this.queue.length > 0) {
      const { fn, resolve, reject } = this.queue.shift()!;
      try {
        resolve(await fn());
      } catch (error) {
        reject(error);
      }
      if (this.queue.length > 0) {
        await new Promise(r => setTimeout(r, this.intervalMs));
      }
    }
    this.processing = false;
  }
}

// Usage: 8 requests/second max
const queue = new RequestQueue(8);
const client = new LinearClient({ apiKey: process.env.LINEAR_API_KEY! });

const teamResults = await Promise.all(
  teamIds.map(id => queue.enqueue(() => client.team(id)))
);

Step 4: Reduce Query Complexity

// HIGH COMPLEXITY (~12,500 pts):
// 250 issues * (1 issue + 50 labels * 0.1 per field) = expensive
// const heavy = await client.issues({ first: 250 });

// LOW COMPLEXITY (~55 pts):
// 50 issues * (5 fields * 0.1 + 1 object) = cheap
const light = await client.issues({
  first: 50,
  filter: { team: { id: { eq: teamId } } },
});

// Use rawRequest for minimal field selection
const minimal = await client.client.rawRequest(`
  query { issues(first: 50) { nodes { id identifier title priority } } }
`);

// Sort by updatedAt to get fresh data first, avoid paginating everything
const fresh = await client.issues({
  first: 50,
  orderBy: "updatedAt",
  filter: { updatedAt: { gte: lastSyncTime } },
});

Step 5: Batch Mutations

Combine multiple mutations into one GraphQL request.

// Instead of 100 separate issueUpdate calls (~100 requests):
async function batchUpdatePriority(client: LinearClient, issueIds: string[], priority: number) {
  const chunkSize = 20; // Keep each batch under complexity limit
  for (let i = 0; i < issueIds.length; i += chunkSize) {
    const chunk = issueIds.slice(i, i + chunkSize);
    const mutations = chunk.map((id, j) =>
      `u${j}: issueUpdate(id: "${id}", input: { priority: ${priority} }) { success }`
    ).join("\n");

    await queue.enqueue(() =>
      client.client.rawRequest(`mutation BatchUpdate { ${mutations} }`)
    );
  }
}

// Batch archive
async function batchArchive(client: LinearClient, issueIds: string[]) {
  for (let i = 0; i < issueIds.length; i += 20) {
    const chunk = issueIds.slice(i, i + 20);
    const mutations = chunk.map((id, j) =>
      `a${j}: issueArchive(id: "${id}") { success }`
    ).join("\n");

    await client.client.rawRequest(`mutation { ${mutations} }`);
  }
}

Step 6: Rate Limit Monitor

class RateLimitMonitor {
  private remaining = { requests: 5000, complexity: 250000 };

  update(headers: Headers) {
    const reqRemaining = headers.get("x-ratelimit-requests-remaining");
    const cxRemaining = headers.get("x-ratelimit-complexity-remaining");
    if (reqRemaining) this.remaining.requests = parseInt(reqRemaining);
    if (cxRemaining) this.remaining.complexity = parseInt(cxRemaining);
  }

  isLow(): boolean {
    return this.remaining.requests < 100 || this.remaining.complexity < 5000;
  }

  getStatus() {
    return {
      requests: this.remaining.requests,
      complexity: this.remaining.complexity,
      healthy: !this.isLow(),
    };
  }
}

Error Handling

ErrorCauseSolution
HTTP 429Request or complexity budget exceededParse headers, back off exponentially
Query complexity too highSingle query > 10,000 ptsReduce first to 50, remove nested relations
Burst of 429s on startupInit fetches too much dataStagger startup queries, cache static data
Timeout on SDK callServer under loadAdd 30s timeout, retry once

Examples

Rate Limit Status Check

curl -s -I -X POST https://api.linear.app/graphql \
  -H "Authorization: $LINEAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ viewer { id } }"}' 2>&1 | grep -i ratelimit

Safe Bulk Import

const rlClient = new RateLimitedClient(process.env.LINEAR_API_KEY!);
const items = [/* issues to import */];

for (let i = 0; i < items.length; i++) {
  await rlClient.withRetry(() =>
    rlClient.sdk.createIssue({ teamId: "team-uuid", title: items[i].title })
  );
  if ((i + 1) % 50 === 0) console.log(`Imported ${i + 1}/${items.length}`);
}

Resources

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.

6532

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.

9029

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

15922

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.

4915

designing-database-schemas

jeremylongshore

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

12014

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.

5110

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.

1,4071,302

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.

1,2201,024

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."

9001,013

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.

958658

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.

970608

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,033496

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.