# Tara API Rate Limiting

Documentation for API rate limits, throttling policies, and best practices for
staying within limits.

## Overview

The Tara API implements rate limiting to ensure fair usage, protect against
abuse, and maintain service quality for all users. Rate limits are applied at
multiple levels and vary by endpoint type and user tier.

## Rate Limit Tiers

### By Authentication Status

| Tier            | Requests/Min | Requests/Hour | Concurrent |
| --------------- | ------------ | ------------- | ---------- |
| Unauthenticated | 20           | 100           | 5          |
| Free User       | 60           | 1,000         | 10         |
| Premium User    | 120          | 3,000         | 20         |
| Enterprise      | 600          | 30,000        | 100        |

### By Endpoint Type

| Endpoint Category  | Limit/Min | Limit/Hour | Notes                    |
| ------------------ | --------- | ---------- | ------------------------ |
| Authentication     | 10        | 50         | Stricter for security    |
| Read (GET)         | 120       | 3,000      | Standard read operations |
| Write (POST/PATCH) | 60        | 1,500      | Create/update operations |
| Delete (DELETE)    | 30        | 300        | Destructive operations   |
| Search             | 30        | 500        | Resource-intensive       |
| Media/Streaming    | 30        | 500        | High bandwidth           |

### Special Endpoint Limits

| Endpoint                     | Limit       | Window | Notes          |
| ---------------------------- | ----------- | ------ | -------------- |
| `POST /auth/login`           | 5 attempts  | 15 min | Per IP + email |
| `POST /auth/register`        | 3 attempts  | 1 hour | Per IP         |
| `POST /auth/forgot-password` | 3 attempts  | 1 hour | Per email      |
| `POST /auth/refresh`         | 30 requests | 1 min  | Per user       |
| `GET /meditations/search`    | 30 requests | 1 min  | Per user       |
| `GET /meditations/:id/audio` | 10 requests | 1 min  | Per meditation |

## Rate Limit Headers

Every API response includes rate limit information in the headers:

```http
HTTP/1.1 200 OK
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 115
X-RateLimit-Reset: 1705316700
X-RateLimit-Policy: authenticated-standard
```

### Header Definitions

| Header                  | Description                            |
| ----------------------- | -------------------------------------- |
| `X-RateLimit-Limit`     | Maximum requests allowed in the window |
| `X-RateLimit-Remaining` | Requests remaining in current window   |
| `X-RateLimit-Reset`     | Unix timestamp when the window resets  |
| `X-RateLimit-Policy`    | Policy name applied to the request     |

### Rate Limit Exceeded Response

When rate limited, you'll receive a `429 Too Many Requests` response:

```http
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705316700
Retry-After: 60
```

```json
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests. Please slow down.",
    "details": [
      {
        "field": "retryAfter",
        "message": "60"
      },
      {
        "field": "limit",
        "message": "120"
      },
      {
        "field": "window",
        "message": "60"
      }
    ],
    "hint": "Wait 60 seconds before making another request"
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

## Rate Limit Algorithms

### Sliding Window

Most endpoints use a sliding window algorithm:

```
┌────────────────────────────────────────────────────────────────────┐
│                     Sliding Window Algorithm                        │
├────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Time ─────────────────────────────────────────────────────────►   │
│                                                                     │
│  Window 1    ├──────────────────────────┤                          │
│              │  Count: 45/60            │                          │
│                                                                     │
│  Window 2         ├──────────────────────────┤                     │
│                   │  Count: 52/60            │                      │
│                                                                     │
│  Current             ├──────────────────────────┤                  │
│                      │  Count: 58/60            │  ◄── 2 remaining │
│                                                                     │
│  Each request slides the window forward by the request timestamp   │
│                                                                     │
└────────────────────────────────────────────────────────────────────┘
```

### Token Bucket

High-throughput endpoints use token bucket algorithm:

```
┌────────────────────────────────────────────────────────────────────┐
│                      Token Bucket Algorithm                         │
├────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌─────────────────┐                                               │
│  │  Token Bucket   │  Capacity: 120 tokens                         │
│  │  ●●●●●●●●●●●●  │  Current: 115 tokens                          │
│  │  ●●●●●●●●●●●●  │                                                │
│  │  ●●●●●●●●●●●   │  Refill rate: 2 tokens/second                  │
│  └─────────────────┘                                               │
│                                                                     │
│  Each request consumes 1 token                                      │
│  Tokens refill continuously at the refill rate                     │
│  Burst capacity allows handling traffic spikes                     │
│                                                                     │
└────────────────────────────────────────────────────────────────────┘
```

## Handling Rate Limits

### Best Practices

#### 1. Monitor Rate Limit Headers

```typescript
class TaraApiClient {
  private rateLimitRemaining: number = Infinity;
  private rateLimitReset: number = 0;

  async request(endpoint: string, options: RequestInit) {
    // Check if we're close to the limit
    if (this.rateLimitRemaining < 5) {
      const waitTime = this.rateLimitReset - Date.now();
      if (waitTime > 0) {
        await this.sleep(waitTime);
      }
    }

    const response = await fetch(`${this.baseUrl}${endpoint}`, options);

    // Update rate limit tracking
    this.rateLimitRemaining = parseInt(
      response.headers.get('X-RateLimit-Remaining') || 'Infinity'
    );
    this.rateLimitReset =
      parseInt(response.headers.get('X-RateLimit-Reset') || '0') * 1000;

    return response;
  }
}
```

#### 2. Implement Exponential Backoff

```typescript
async function requestWithBackoff<T>(
  fn: () => Promise<T>,
  maxRetries: number = 5
): Promise<T> {
  let retries = 0;

  while (true) {
    try {
      return await fn();
    } catch (error) {
      if (error.code !== 'RATE_LIMIT_EXCEEDED' || retries >= maxRetries) {
        throw error;
      }

      // Use Retry-After header if available
      const retryAfter = error.details?.find(
        (d: any) => d.field === 'retryAfter'
      )?.message;

      const delay = retryAfter
        ? parseInt(retryAfter) * 1000
        : Math.min(1000 * Math.pow(2, retries) + Math.random() * 1000, 60000);

      console.log(
        `Rate limited. Waiting ${delay}ms before retry ${retries + 1}`
      );
      await sleep(delay);
      retries++;
    }
  }
}
```

#### 3. Request Batching

Instead of making many individual requests, batch them:

```typescript
// Bad: Individual requests
async function getMeditations(ids: string[]) {
  return Promise.all(
    ids.map((id) => client.meditations.get(id)) // May hit rate limit!
  );
}

// Good: Batch request
async function getMeditations(ids: string[]) {
  return client.meditations.list({
    ids: ids.join(','),
    limit: ids.length,
  });
}
```

#### 4. Local Caching

Cache responses to reduce API calls:

```typescript
import { LRUCache } from 'lru-cache';

const meditationCache = new LRUCache<string, Meditation>({
  max: 100,
  ttl: 1000 * 60 * 5, // 5 minutes
});

async function getMeditation(id: string): Promise<Meditation> {
  // Check cache first
  const cached = meditationCache.get(id);
  if (cached) {
    return cached;
  }

  // Fetch from API
  const meditation = await client.meditations.get(id);
  meditationCache.set(id, meditation);

  return meditation;
}
```

#### 5. Request Debouncing

For user-initiated actions like search:

```typescript
import { debounce } from 'lodash';

const searchMeditations = debounce(
  async (query: string) => {
    const results = await client.meditations.search({ q: query });
    setSearchResults(results);
  },
  300 // Wait 300ms after user stops typing
);

// In component
<TextInput
  onChangeText={text => {
    setQuery(text);
    searchMeditations(text);
  }}
/>
```

#### 6. Queue Management

For background operations:

```typescript
import PQueue from 'p-queue';

// Create a queue with concurrency limit
const queue = new PQueue({
  concurrency: 5,
  interval: 1000,
  intervalCap: 10, // Max 10 requests per second
});

// Add requests to queue
async function syncMeditations(ids: string[]) {
  const results = await Promise.all(
    ids.map((id) => queue.add(() => client.meditations.get(id)))
  );
  return results;
}
```

## Rate Limit Exemptions

### WebSocket Connections

WebSocket connections for real-time features are not subject to HTTP rate limits
but have their own limits:

| Limit Type       | Value | Notes                      |
| ---------------- | ----- | -------------------------- |
| Connections/user | 5     | Max concurrent connections |
| Messages/minute  | 100   | Per connection             |
| Payload size     | 64KB  | Max message size           |

### Webhooks

Incoming webhooks from payment providers (Apple, Google) are exempt from rate
limits but are verified for authenticity.

### Health Endpoints

The `/health` and `/ready` endpoints are not rate limited to support health
monitoring.

## Monitoring Usage

### API Dashboard

Monitor your API usage in the developer dashboard:

1. Visit https://dashboard.tara.app
2. Navigate to API → Usage
3. View request counts, rate limit hits, and trends

### Usage Metrics

The dashboard provides:

- Requests per endpoint
- Rate limit encounters
- Response time percentiles
- Error rates by type

### Alerts

Set up alerts for:

- Rate limit threshold approaching (e.g., 80% of limit)
- Unusual traffic patterns
- Error rate spikes

## Enterprise Rate Limits

For applications requiring higher limits:

### Request Higher Limits

1. Contact sales@tara.app
2. Describe your use case and expected traffic
3. Provide your organization details

### Enterprise Features

- Custom rate limits per endpoint
- Dedicated API infrastructure
- Priority support
- SLA guarantees

## FAQ

### Q: Why am I getting rate limited with normal usage?

Common causes:

1. **Polling too frequently** - Use webhooks instead
2. **Not caching responses** - Implement local caching
3. **Making sequential requests** - Use batch endpoints
4. **Multiple clients with same credentials** - Implement request coordination

### Q: Can I request a rate limit increase?

Yes, for legitimate use cases:

1. Premium users can request temporary increases for events
2. Enterprise plans include custom limits
3. Contact support with your use case details

### Q: Are rate limits shared across devices?

Rate limits are applied per user (for authenticated requests) or per IP (for
unauthenticated requests). Multiple devices logged into the same account share
the user's rate limit.

### Q: What happens to queued requests when rate limited?

Requests that arrive while rate limited receive an immediate 429 response. It's
the client's responsibility to implement retry logic.

### Q: Do WebSocket messages count toward rate limits?

WebSocket messages have separate limits from HTTP requests. Real-time updates
don't consume your HTTP rate limit allowance.

## Support

For rate limit issues:

- **Emergency increases**: support@tara.app (Enterprise only)
- **General questions**: api-support@tara.app
- **Enterprise plans**: sales@tara.app
