MA

maintainx-cost-tuning

Offers strategies for optimizing MaintainX API costs through caching, batching, and usage tracking.

Install

mkdir -p .claude/skills/maintainx-cost-tuning && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6622" && unzip -o skill.zip -d .claude/skills/maintainx-cost-tuning && rm skill.zip

Installs to .claude/skills/maintainx-cost-tuning

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Optimize MaintainX API usage for cost efficiency.
49 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Track API request volume per endpoint
  • Implement response caching with resource-specific time-to-live (TTL)
  • Replace polling with webhook-driven synchronization
  • Apply smart polling strategies using `updatedAtGte` filters
  • Deduplicate concurrent identical API requests

How it works

This skill optimizes MaintainX API usage by tracking request volume, caching responses, and replacing continuous polling with event-driven webhooks. It also includes smart polling and request deduplication to reduce API calls.

Inputs & outputs

You give it
MaintainX API requests, endpoint paths, cache keys, webhook events
You get back
API usage reports, cached API responses, webhook-triggered data synchronization, deduplicated requests

When to use maintainx-cost-tuning

  • Reduce MaintainX API costs
  • Track MaintainX API usage
  • Optimize polling strategies
  • Implement request caching

About this skill

MaintainX Cost Tuning

Overview

Reduce MaintainX API request volume and optimize costs through caching, webhook-driven sync, request batching, and smart polling strategies.

Prerequisites

  • MaintainX integration deployed and working
  • Redis or in-memory cache available
  • Baseline API usage metrics

Instructions

Step 1: Request Volume Tracking

// src/cost/usage-tracker.ts

class ApiUsageTracker {
  private counts: Map<string, number> = new Map();
  private startTime = Date.now();

  record(endpoint: string) {
    const key = endpoint.split('?')[0]; // Strip query params
    this.counts.set(key, (this.counts.get(key) || 0) + 1);
  }

  report() {
    const elapsed = (Date.now() - this.startTime) / 1000 / 60; // minutes
    console.log(`\n=== API Usage Report (${elapsed.toFixed(1)} min) ===`);
    const sorted = [...this.counts.entries()].sort((a, b) => b[1] - a[1]);
    for (const [endpoint, count] of sorted) {
      const rate = (count / elapsed).toFixed(1);
      console.log(`  ${endpoint}: ${count} calls (${rate}/min)`);
    }
    console.log(`  TOTAL: ${[...this.counts.values()].reduce((a, b) => a + b, 0)} calls`);
  }
}

export const tracker = new ApiUsageTracker();
// Report every 10 minutes
setInterval(() => tracker.report(), 600_000);

Step 2: Response Caching

// src/cost/cached-client.ts

interface CacheEntry<T> {
  data: T;
  expiresAt: number;
}

class CachedMaintainXClient {
  private cache = new Map<string, CacheEntry<any>>();
  private client: MaintainXClient;

  // TTL per resource type (in seconds)
  private ttl: Record<string, number> = {
    '/users': 300,       // 5 min - users rarely change
    '/locations': 300,   // 5 min - locations are static
    '/assets': 120,      // 2 min - assets change infrequently
    '/workorders': 30,   // 30 sec - work orders change often
    '/teams': 600,       // 10 min - teams are very static
  };

  constructor(client: MaintainXClient) {
    this.client = client;
  }

  async get<T>(endpoint: string, params?: any): Promise<T> {
    const cacheKey = `${endpoint}:${JSON.stringify(params || {})}`;
    const cached = this.cache.get(cacheKey);

    if (cached && cached.expiresAt > Date.now()) {
      console.log(`[CACHE HIT] ${endpoint}`);
      return cached.data;
    }

    const basePath = '/' + endpoint.split('/').filter(Boolean)[0];
    const ttlSec = this.ttl[basePath] || 60;

    const data = await this.client.request('GET', endpoint, undefined, params);
    this.cache.set(cacheKey, {
      data,
      expiresAt: Date.now() + ttlSec * 1000,
    });

    tracker.record(endpoint);
    return data as T;
  }

  invalidate(pattern: string) {
    for (const key of this.cache.keys()) {
      if (key.startsWith(pattern)) {
        this.cache.delete(key);
      }
    }
  }
}

Step 3: Webhook-Driven Sync (Replace Polling)

Polling every 30 seconds costs thousands of requests/day per endpoint. Webhooks reduce this to near zero.

// Before: Polling (expensive)
// Calculation: 1 request every 30 sec = 2 req/min * 60 min * 24 hr = ~2880 req/day
setInterval(async () => {
  const { workOrders } = await client.getWorkOrders({ status: 'OPEN' });
  await syncToLocalDb(workOrders);
}, 30_000);

// After: Webhook-driven (near zero cost)
app.post('/webhooks/maintainx', async (req, res) => {
  const { event, data } = req.body;
  if (event === 'workorder.updated' || event === 'workorder.created') {
    await upsertWorkOrder(data);  // Only sync what changed
  }
  res.status(200).json({ ok: true });
});

Cost savings: From thousands of daily polling requests to ~50 req/day (webhook-driven deltas only).

Step 4: Smart Polling with Conditional Requests

When webhooks are not available, reduce unnecessary fetches:

// Only fetch if data has changed since last check
async function smartPoll(client: MaintainXClient, state: { lastModified?: string }) {
  const response = await client.getWorkOrders({
    updatedAtGte: state.lastModified || new Date(0).toISOString(),
    limit: 100,
  });

  if (response.workOrders.length === 0) {
    console.log('No changes since last poll');
    return [];
  }

  state.lastModified = new Date().toISOString();
  return response.workOrders;
}

Step 5: Request Deduplication

// Deduplicate concurrent identical requests
const inFlight = new Map<string, Promise<any>>();

async function deduplicatedGet(client: MaintainXClient, endpoint: string): Promise<any> {
  if (inFlight.has(endpoint)) {
    return inFlight.get(endpoint)!;
  }

  const promise = client.request('GET', endpoint);
  inFlight.set(endpoint, promise);

  try {
    return await promise;
  } finally {
    inFlight.delete(endpoint);
  }
}

Output

  • API usage tracking with per-endpoint request counts
  • Response caching with resource-specific TTLs
  • Webhook-driven sync replacing expensive polling loops
  • Smart polling with updatedAtGte filter for change detection
  • Request deduplication preventing concurrent identical calls

Error Handling

IssueCauseSolution
Stale cache dataTTL too long for volatile resourcesReduce TTL for /workorders to 15-30s
Webhook delivery failuresEndpoint down or unreachableFall back to polling with longer interval
Cache memory growthNo eviction policySet max cache size, use LRU eviction
Duplicate webhook eventsMaintainX retriesDeduplicate by event ID (see webhooks skill)

Resources

Next Steps

For architecture patterns, see maintainx-reference-architecture.

Examples

Redis-based cache for production:

import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function cachedGet(key: string, ttlSec: number, fetcher: () => Promise<any>) {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const data = await fetcher();
  await redis.setex(key, ttlSec, JSON.stringify(data));
  return data;
}

// Usage
const workOrders = await cachedGet(
  'maintainx:workorders:open',
  30,
  () => client.getWorkOrders({ status: 'OPEN' }),
);

When not to use it

  • When the TTL for a resource is too long for volatile data
  • When webhook delivery failures require a fallback to polling
  • When cache memory growth is not managed by an eviction policy

Prerequisites

MaintainX integration deployed and workingRedis or in-memory cache availableBaseline API usage metrics

Limitations

  • Stale cache data can occur if TTL is too long for volatile resources
  • Webhook delivery failures may necessitate a fallback to polling
  • Cache memory can grow without an eviction policy

How it compares

This skill reduces MaintainX API costs by implementing caching and webhooks, which is more efficient than making direct, unoptimized API calls or continuous polling.

Compared to similar skills

maintainx-cost-tuning side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
maintainx-cost-tuning (this skill)127dReviewIntermediate
nextjs-developer3282moNo flagsAdvanced
angular1004moReviewAdvanced
chrome-devtools417moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

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.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

nextjs-developer

zenobi-us

Expert Next.js developer mastering Next.js 14+ with App Router and full-stack features. Specializes in server components, server actions, performance optimization, and production deployment with focus on building fast, SEO-friendly applications.

328531

angular

sickn33

Modern Angular (v20+) expert with deep knowledge of Signals, Standalone Components, Zoneless applications, SSR/Hydration, and reactive patterns. Use PROACTIVELY for Angular development, component architecture, state management, performance optimization, and migration to modern patterns.

100129

chrome-devtools

mrgoonie

Browser automation, debugging, and performance analysis using Puppeteer CLI scripts. Use for automating browsers, taking screenshots, analyzing performance, monitoring network traffic, web scraping, form automation, and JavaScript debugging.

41157

flutter-expert

sickn33

Master Flutter development with Dart 3, advanced widgets, and multi-platform deployment. Handles state management, animations, testing, and performance optimization for mobile, web, desktop, and embedded platforms. Use PROACTIVELY for Flutter architecture, UI implementation, or cross-platform features.

73125

bullmq-specialist

davila7

BullMQ expert for Redis-backed job queues, background processing, and reliable async execution in Node.js/TypeScript applications. Use when: bullmq, bull queue, redis queue, background job, job queue.

2595

reviewing-nextjs-16-patterns

djankies

Review code for Next.js 16 compliance - security patterns, caching, breaking changes. Use when reviewing Next.js code, preparing for migration, or auditing for violations.

11106

Search skills

Search the agent skills registry