Eve library

Rate Limiting Documentation

Guide

Revision 1

On this page

Complete guide to Yemaya API rate limits.

Overview#

Rate limiting protects the API from abuse and ensures fair usage for all users. Limits are applied per API key or user token.


Rate Limit Tiers#

By Authentication#

Type Limit Window
Unauthenticated 60 requests 1 minute
Authenticated 1,000 requests 1 minute
API Key (Standard) 1,000 requests 1 minute
API Key (Pro) 5,000 requests 1 minute
API Key (Enterprise) 20,000 requests 1 minute

By Endpoint Category#

Category Limit Window Notes
General API 1,000/min 1 minute Most endpoints
Authentication 20/min 1 minute Login, register
Generation (3D) 30/min 1 minute Text-to-3D, image-to-3D
Generation (Audio) 50/min 1 minute Music, voice
Upload 100/min 1 minute File uploads
WebSocket 100 connections per user Concurrent

Rate Limit Headers#

Every API response includes rate limit headers:

http
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 997
X-RateLimit-Reset: 1705320000
X-RateLimit-Reset-After: 45
Header Description
X-RateLimit-Limit Maximum requests in window
X-RateLimit-Remaining Remaining requests in window
X-RateLimit-Reset Unix timestamp when limit resets
X-RateLimit-Reset-After Seconds until limit resets

Rate Limit Response#

When rate limited, the API returns:

http
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 45
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705320000

{
  "success": false,
  "error": {
    "code": "RATE_LIMITED",
    "message": "Too many requests. Please retry after 45 seconds.",
    "details": {
      "limit": 1000,
      "remaining": 0,
      "resetAt": "2024-01-15T10:30:00Z",
      "retryAfter": 45
    }
  }
}

Handling Rate Limits#

Basic Retry Logic#

typescript
async function fetchWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3
): Promise<Response> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status === 429) {
      const retryAfter = parseInt(response.headers.get('Retry-After') || '60');

      console.log(`Rate limited. Retrying in ${retryAfter}s...`);
      await sleep(retryAfter * 1000);
      continue;
    }

    return response;
  }

  throw new Error('Max retries exceeded');
}

Exponential Backoff#

typescript
async function fetchWithExponentialBackoff(
  url: string,
  options: RequestInit,
  maxRetries = 5
): Promise<Response> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);

      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '0');

        // Use Retry-After or exponential backoff
        const delay =
          retryAfter > 0
            ? retryAfter * 1000
            : Math.min(1000 * Math.pow(2, attempt), 60000);

        console.log(`Rate limited. Retrying in ${delay}ms...`);
        await sleep(delay);
        continue;
      }

      return response;
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;

      const delay = Math.min(1000 * Math.pow(2, attempt), 60000);
      await sleep(delay);
    }
  }

  throw new Error('Max retries exceeded');
}

SDK Rate Limit Handling#

The official SDKs handle rate limits automatically:

typescript
// TypeScript SDK - Auto-retry enabled by default
const client = new YemayaClient({
  apiKey: 'your-key',
  retry: {
    maxRetries: 3,
    backoff: 'exponential',
  },
});

// Disable auto-retry
const client = new YemayaClient({
  apiKey: 'your-key',
  retry: false,
});
python
# Python SDK
from yemaya import YemayaClient

client = YemayaClient(
    api_key="your-key",
    max_retries=3,
    backoff="exponential"
)

Request Queuing#

For high-volume applications, implement request queuing:

typescript
class RateLimitedQueue {
  private queue: Array<() => Promise<any>> = [];
  private processing = false;
  private remaining: number = 1000;
  private resetAt: number = 0;

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

  private async process() {
    if (this.processing) return;
    this.processing = true;

    while (this.queue.length > 0) {
      // Check if we need to wait
      if (this.remaining <= 0 && Date.now() < this.resetAt) {
        const waitTime = this.resetAt - Date.now();
        await sleep(waitTime);
      }

      const request = this.queue.shift()!;
      await request();
    }

    this.processing = false;
  }

  updateLimits(remaining: number, resetAt: number) {
    this.remaining = remaining;
    this.resetAt = resetAt;
  }
}

// Usage
const queue = new RateLimitedQueue();

const results = await Promise.all([
  queue.add(() => client.projects.list()),
  queue.add(() => client.assets.list('proj_123')),
  queue.add(() => client.threeD.generate({ prompt: 'cat' })),
]);

Bulk Operations#

For operations on multiple items, use bulk endpoints:

typescript
// ❌ Bad - Makes 100 individual requests
for (const id of assetIds) {
  await client.assets.get(projectId, id);
}

// ✅ Good - Single bulk request
const assets = await client.assets.getBulk(projectId, assetIds);

Available Bulk Endpoints#

Endpoint Method Description
/assets/bulk POST Get multiple assets
/3d/batch POST Generate multiple models
/audio/batch POST Generate multiple audio
/npcs/batch/chat POST Chat with multiple NPCs

Monitoring Usage#

Check Current Usage#

http
GET /v1/usage/rate-limits
Authorization: Bearer <token>

Response:

json
{
  "success": true,
  "data": {
    "tier": "pro",
    "limits": {
      "general": {
        "limit": 5000,
        "remaining": 4850,
        "resetAt": "2024-01-15T10:30:00Z"
      },
      "generation": {
        "limit": 100,
        "remaining": 85,
        "resetAt": "2024-01-15T10:30:00Z"
      },
      "upload": {
        "limit": 500,
        "remaining": 490,
        "resetAt": "2024-01-15T10:30:00Z"
      }
    }
  }
}

Usage Analytics#

http
GET /v1/usage/analytics?period=7d
Authorization: Bearer <token>

Response:

json
{
  "success": true,
  "data": {
    "period": "7d",
    "totalRequests": 15420,
    "rateLimitHits": 23,
    "byEndpoint": {
      "/projects": 2500,
      "/assets": 5000,
      "/3d/generate": 1200
    },
    "byDay": [
      { "date": "2024-01-14", "requests": 2100 },
      { "date": "2024-01-15", "requests": 2300 }
    ]
  }
}

Best Practices#

1. Cache Responses#

typescript
const cache = new Map<string, { data: any; expiry: number }>();

async function cachedFetch(url: string, ttl = 60000) {
  const cached = cache.get(url);

  if (cached && Date.now() < cached.expiry) {
    return cached.data;
  }

  const response = await fetch(url);
  const data = await response.json();

  cache.set(url, {
    data,
    expiry: Date.now() + ttl,
  });

  return data;
}

2. Use Webhooks#

Instead of polling, use webhooks for real-time updates:

typescript
// ❌ Bad - Polling every 5 seconds
setInterval(async () => {
  const status = await client.jobs.get(jobId);
  if (status === 'completed') {
    // ...
  }
}, 5000);

// ✅ Good - Use webhooks
// Register webhook for generation.completed event

3. Batch Requests#

typescript
// ❌ Bad - 10 separate requests
const projects = [];
for (let i = 1; i <= 10; i++) {
  const page = await client.projects.list({ page: i, limit: 20 });
  projects.push(...page.data);
}

// ✅ Good - Increase limit, fewer requests
const allProjects = await client.projects.list({ limit: 200 });

4. Implement Circuit Breaker#

typescript
class CircuitBreaker {
  private failures = 0;
  private lastFailure = 0;
  private state: 'closed' | 'open' | 'half-open' = 'closed';

  constructor(
    private threshold = 5,
    private resetTimeout = 30000
  ) {}

  async execute<T>(fn: () => Promise<T>): Promise<T> {
    if (this.state === 'open') {
      if (Date.now() - this.lastFailure > this.resetTimeout) {
        this.state = 'half-open';
      } else {
        throw new Error('Circuit breaker is open');
      }
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }

  private onSuccess() {
    this.failures = 0;
    this.state = 'closed';
  }

  private onFailure() {
    this.failures++;
    this.lastFailure = Date.now();

    if (this.failures >= this.threshold) {
      this.state = 'open';
    }
  }
}

const circuitBreaker = new CircuitBreaker();

await circuitBreaker.execute(() => client.threeD.generate({ prompt: 'cat' }));

5. Monitor and Alert#

typescript
// Track rate limit usage
let consecutiveRateLimits = 0;

client.on('response', (response) => {
  const remaining = parseInt(
    response.headers.get('X-RateLimit-Remaining') || '0'
  );

  if (response.status === 429) {
    consecutiveRateLimits++;

    if (consecutiveRateLimits >= 3) {
      alertOps('Multiple rate limits hit - review usage');
    }
  } else {
    consecutiveRateLimits = 0;
  }

  // Alert when approaching limit
  if (remaining < 100) {
    console.warn(`Rate limit warning: ${remaining} requests remaining`);
  }
});

Increasing Limits#

Upgrade Plan#

Contact sales for higher rate limits:

Plan General Generation Price
Standard 1,000/min 30/min Free
Pro 5,000/min 100/min $49/mo
Enterprise Custom Custom Contact

Request Temporary Increase#

For specific events (launches, demos), request temporary increases:

http
POST /v1/support/rate-limit-increase
Authorization: Bearer <token>
Content-Type: application/json

{
  "reason": "Product launch event",
  "requestedLimit": 10000,
  "duration": "24h",
  "startDate": "2024-01-20T00:00:00Z"
}

Common Errors#

RATE_LIMITED#

json
{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Too many requests"
  }
}

Solution: Wait for Retry-After seconds and retry.

CONCURRENT_LIMIT_EXCEEDED#

json
{
  "error": {
    "code": "CONCURRENT_LIMIT_EXCEEDED",
    "message": "Too many concurrent requests"
  }
}

Solution: Reduce concurrent request count.

DAILY_LIMIT_EXCEEDED#

json
{
  "error": {
    "code": "DAILY_LIMIT_EXCEEDED",
    "message": "Daily request limit exceeded"
  }
}

Solution: Wait until next day or upgrade plan.


See Also#