Skip to content
linear-cost-tuning logo

Linear Cost Tuning

linear-cost-tuning

Optimize Linear API usage and manage costs effectively. Use when reducing API calls, managing rate limits efficiently, or optimizing integration costs. Trigger with phrases like "linear cost", "reduce linear API calls", "linear efficiency", "linear API usage", "optimize linear costs".

SKILL.md

Full skill instructions

Linear Cost Tuning

Overview

Optimize Linear API usage to maximize efficiency and minimize costs.

Prerequisites

  • Working Linear integration
  • Monitoring in place
  • Understanding of usage patterns

Cost Factors

API Request Costs

FactorImpactOptimization Strategy
Request countDirect rate limitBatch operations
Query complexityComplexity limitMinimal field selection
Payload sizeBandwidth/​latencyPagination, filtering
Webhook volumeProcessing costsEvent filtering

Instructions

Step 1: Audit Current Usage

// lib/​usage-tracker.ts
interface UsageStats {
  requests: number;
  complexity: number;
  bytesTransferred: number;
  period: { start: Date; end: Date };
}

class UsageTracker {
  private stats: UsageStats = {
    requests: 0,
    complexity: 0,
    bytesTransferred: 0,
    period: { start: new Date(), end: new Date() },
  };

  recordRequest(complexity: number, bytes: number): void {
    this.stats.requests++;
    this.stats.complexity += complexity;
    this.stats.bytesTransferred += bytes;
    this.stats.period.end = new Date();
  }

  getStats(): UsageStats {
    return { ...this.stats };
  }

  getDaily(): {
    avgRequestsPerHour: number;
    avgComplexityPerRequest: number;
    projectedMonthlyRequests: number;
  } {
    const hours =
      (this.stats.period.end.getTime() - this.stats.period.start.getTime()) /
      (1000 * 60 * 60);

    return {
      avgRequestsPerHour: this.stats.requests / Math.max(hours, 1),
      avgComplexityPerRequest: this.stats.complexity / Math.max(this.stats.requests, 1),
      projectedMonthlyRequests: (this.stats.requests / Math.max(hours, 1)) * 24 * 30,
    };
  }

  reset(): void {
    this.stats = {
      requests: 0,
      complexity: 0,
      bytesTransferred: 0,
      period: { start: new Date(), end: new Date() },
    };
  }
}

export const usageTracker = new UsageTracker();

Step 2: Reduce Request Volume

Polling vs Webhooks:

// BAD: Polling every minute
setInterval(async () => {
  const issues = await client.issues({ first: 100 });
  await syncIssues(issues.nodes);
}, 60000);

// GOOD: Use webhooks for real-time updates
// See linear-webhooks-events skill
app.post("/​webhooks/​linear", async (req, res) => {
  const event = req.body;
  await handleEvent(event);
  res.sendStatus(200);
});

Conditional Fetching:

// lib/​conditional-fetch.ts
interface ETagCache {
  data: any;
  etag: string;
  timestamp: Date;
}

const etagCache = new Map<string, ETagCache>();

async function fetchWithETag(key: string, fetcher: () => Promise<any>) {
  const cached = etagCache.get(key);

  // Only fetch if cache is stale (> 5 minutes)
  if (cached && Date.now() - cached.timestamp.getTime() < 5 * 60 * 1000) {
    return cached.data;
  }

  const data = await fetcher();
  etagCache.set(key, {
    data,
    etag: JSON.stringify(data).slice(0, 50), // Simple hash
    timestamp: new Date(),
  });

  return data;
}

Step 3: Optimize Query Complexity

Calculate Complexity:

// Linear complexity estimation
// - Each field costs 1
// - Each connection costs 1 + (first * child_complexity)
// - Nested connections multiply

// BAD: High complexity query (~500 complexity)
const expensiveQuery = `
  query {
    issues(first: 50) {
      nodes {
        id
        title
        assignee { name }
        labels { nodes { name } }
        comments(first: 10) {
          nodes { body user { name } }
        }
      }
    }
  }
`;

// GOOD: Low complexity query (~100 complexity)
const cheapQuery = `
  query {
    issues(first: 50) {
      nodes {
        id
        identifier
        title
        priority
      }
    }
  }
`;

Step 4: Implement Request Coalescing

// lib/​coalesce.ts
class RequestCoalescer {
  private pending = new Map<string, Promise<any>>();

  async execute<T>(key: string, fn: () => Promise<T>): Promise<T> {
    // If same request is already in flight, reuse it
    const existing = this.pending.get(key);
    if (existing) {
      return existing;
    }

    const promise = fn().finally(() => {
      this.pending.delete(key);
    });

    this.pending.set(key, promise);
    return promise;
  }
}

const coalescer = new RequestCoalescer();

// Multiple simultaneous calls reuse the same request
const [teams1, teams2, teams3] = await Promise.all([
  coalescer.execute("teams", () => client.teams()),
  coalescer.execute("teams", () => client.teams()), // Reuses first request
  coalescer.execute("teams", () => client.teams()), // Reuses first request
]);

Step 5: Webhook Event Filtering

// Only process relevant events
async function shouldProcessEvent(event: any): boolean {
  // Skip events from bots
  if (event.data?.actor?.isBot) return false;

  // Only process certain issue states
  if (event.type === "Issue" && event.action === "update") {
    const importantFields = ["state", "priority", "assignee"];
    const changedFields = Object.keys(event.updatedFrom || {});

    if (!changedFields.some(f => importantFields.includes(f))) {
      return false; // Skip trivial updates
    }
  }

  // Only process issues from specific teams
  const allowedTeams = ["ENG", "PROD"];
  if (event.data?.team?.key && !allowedTeams.includes(event.data.team.key)) {
    return false;
  }

  return true;
}

Step 6: Lazy Loading Pattern

// lib/​lazy-client.ts
class LazyLinearClient {
  private client: LinearClient;
  private teamsCache: any[] | null = null;
  private statesCache = new Map<string, any[]>();

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

  async getTeams() {
    if (!this.teamsCache) {
      const teams = await this.client.teams();
      this.teamsCache = teams.nodes;
    }
    return this.teamsCache;
  }

  async getStatesForTeam(teamKey: string) {
    if (!this.statesCache.has(teamKey)) {
      const teams = await this.client.teams({
        filter: { key: { eq: teamKey } },
      });
      const states = await teams.nodes[0].states();
      this.statesCache.set(teamKey, states.nodes);
    }
    return this.statesCache.get(teamKey)!;
  }

  // Invalidate on known changes
  invalidateTeams() {
    this.teamsCache = null;
    this.statesCache.clear();
  }
}

Cost Reduction Checklist

  • Replace polling with webhooks
  • Implement request caching
  • Use request coalescing
  • Filter webhook events
  • Minimize query complexity
  • Batch related operations
  • Use lazy loading for static data
  • Monitor and track usage

Monitoring Dashboard

// Example metrics to track
const metrics = {
  // Request metrics
  totalRequests: counter("linear_requests_total"),
  requestDuration: histogram("linear_request_duration_seconds"),
  complexityCost: histogram("linear_complexity_cost"),

  // Cache metrics
  cacheHits: counter("linear_cache_hits_total"),
  cacheMisses: counter("linear_cache_misses_total"),

  // Webhook metrics
  webhooksReceived: counter("linear_webhooks_received_total"),
  webhooksFiltered: counter("linear_webhooks_filtered_total"),
};

Resources

Next Steps

Learn production architecture with linear-reference-architecture.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View