maintainx-cost-tuning
Optimize MaintainX API usage for cost efficiency. Use when managing API costs, optimizing request volume, or implementing cost-effective integration patterns with MaintainX. Trigger with phrases like "maintainx cost", "maintainx billing", "reduce maintainx usage", "maintainx api costs", "maintainx optimization".
What this skill does
# 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
```typescript
// 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
```typescript
// 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.
```typescript
// 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:
```typescript
// 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
```typescript
// 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
| Issue | Cause | Solution |
|-------|-------|----------|
| Stale cache data | TTL too long for volatile resources | Reduce TTL for `/workorders` to 15-30s |
| Webhook delivery failures | Endpoint down or unreachable | Fall back to polling with longer interval |
| Cache memory growth | No eviction policy | Set max cache size, use LRU eviction |
| Duplicate webhook events | MaintainX retries | Deduplicate by event ID (see webhooks skill) |
## Resources
- MaintainX API Reference
- [MaintainX Pricing](https://www.getmaintainx.com/pricing)
- [node-cache](https://github.com/node-cache/node-cache) -- In-memory caching for Node.js
## Next Steps
For architecture patterns, see `maintainx-reference-architecture`.
## Examples
**Redis-based cache for production**:
```typescript
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' }),
);
```
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.