> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getsnippets.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Rate Limiting

> Understand API rate limits and how to handle them

## Overview

To ensure fair usage and maintain system performance, the Snippets AI API implements rate limiting specifically for invalid API key attempts.

<Card title="Invalid API Key Block" icon="shield-slash">
  **20 invalid attempts** within a rolling window will result in a **5-minute
  block** for that API key.
</Card>

### General Rate Limit

There is **no general rate limit** for valid API requests. You can make as many valid requests as needed without encountering rate limiting errors, provided your API key is valid and has the necessary permissions.

## How the Invalid API Key Block Works

This security measure helps prevent brute-force attacks on API keys:

* Each API key has a counter for invalid access attempts.
* If 20 invalid attempts are detected within a short rolling window, the API key will be temporarily blocked.
* The block lasts for 5 minutes, after which the key is automatically unblocked, and the counter resets.

### Invalid Attempt Criteria

An "invalid attempt" is counted when:

* An API request is made with a non-existent API key.
* An API request is made with a valid API key, but it lacks the necessary permissions for the requested resource (e.g., wrong team ID).

## Checking Your API Key Status

### Blocked API Key Errors

When your API key is temporarily blocked due to excessive invalid attempts, you'll receive a `403 Forbidden` response (or similar, depending on exact implementation):

```json theme={null}
{
	"success": false,
	"message": "Too many invalid API key attempts. This API key has been temporarily blocked for 5 minutes."
}
```

This response may also include a `Retry-After` header with the number of seconds until the block is lifted.

## Handling Invalid API Key Blocks

### Exponential Backoff (Modified)

If you encounter a `403 Forbidden` error specifically related to an API key block, you should cease attempts for the specified `Retry-After` duration. If no `Retry-After` is provided, assume a 5-minute (300-second) wait.

<CodeGroup>
  ```javascript JavaScript theme={null}
  const axios = require('axios');

  async function makeRequestWithBackoff(url, options, maxRetries = 3) {
  	for (let i = 0; i < maxRetries; i++) {
  		try {
  			const response = await axios(url, options);
  			return response.data;
  		} catch (error) {
  			if (
  				error.response?.status === 403 &&
  				error.response?.data?.message?.includes(
  					'Too many invalid API key attempts'
  				)
  			) {
  				// Get retry-after from header (in seconds), default to 300 (5 minutes)
  				const retryAfter = parseInt(
  					error.response.headers['retry-after'] || 300
  				);

  				const waitTime = retryAfter * 1000;

  				console.log(`API key blocked. Waiting ${waitTime / 1000} seconds...`);
  				await new Promise((resolve) => setTimeout(resolve, waitTime));

  				// Retry the request after the block period
  				continue;
  			}

  			// Re-throw other errors, including other 403s (e.g., permission issues)
  			throw error;
  		}
  	}

  	throw new Error('Max retries exceeded for API key block');
  }

  // Usage
  const result = await makeRequestWithBackoff(
  	'https://www.getsnippets.ai/api/prompts/snippet',
  	{
  		method: 'GET',
  		headers: {
  			Authorization: `Bearer ${API_KEY}`,
  		},
  		params: { id: 'snippet_id' },
  	}
  );
  ```

  ```python Python theme={null}
  import time
  import requests

  def make_request_with_backoff(
      url: str,
      headers: dict,
      params: Optional[dict] = None,
      max_retries: int = 3
  ) -> dict:
      for attempt in range(max_retries):
          try:
              response = requests.get(url, headers=headers, params=params)
              response.raise_for_status()
              return response.json()

          except requests.exceptions.HTTPError as e:
              if e.response.status_code == 403 and "Too many invalid API key attempts" in e.response.json().get("message", ""):
                  # API key blocked - wait and retry
                  retry_after = int(
                      e.response.headers.get('Retry-After', 300)
                  )

                  print(f"API key blocked. Waiting {retry_after} seconds...")
                  time.sleep(retry_after)

                  # Retry the request
                  continue

              # Re-raise other errors, including other 403s
              raise

      raise Exception('Max retries exceeded for API key block')

  # Usage
  result = make_request_with_backoff(
      'https://www.getsnippets.ai/api/prompts/snippet',
      headers={'Authorization': f'Bearer {API_KEY}'},
      params={'id': 'snippet_id'}
  )
  ```
</CodeGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Use Valid API Keys">
    Always ensure you are using a valid and active API key. Double-check your key and its permissions in the Snippets AI dashboard.
  </Accordion>

  {' '}

  <Accordion title="Handle Authentication Errors Properly">
    Distinguish between different 4xx errors. A `401 Unauthorized` means a
    generally invalid key, while a `403 Forbidden` *might* indicate a temporary
    block if the message specifically mentions "Too many invalid API key
    attempts".
  </Accordion>

  {' '}

  <Accordion title="Avoid Brute-Force Attempts">
    Do not repeatedly try invalid API keys. This will lead to temporary blocks.
  </Accordion>

  <Accordion title="Monitor Your Integrations">
    Regularly monitor logs and error reports from your applications to quickly identify if an API key is being blocked.
  </Accordion>
</AccordionGroup>

## FAQs

<AccordionGroup>
  <Accordion title="Is there a general rate limit for valid requests?">
    No, there is no general rate limit for valid API requests. You can make as many valid requests as your account quota allows.
  </Accordion>

  {' '}

  <Accordion title="What happens if my API key is blocked?">
    Your API key will be temporarily blocked for 5 minutes after 20 invalid
    attempts. During this time, all requests with that key will fail.
  </Accordion>

  {' '}

  <Accordion title="Does a blocked key consume API requests?">
    No, requests made with a temporarily blocked API key do not consume from your
    API request quota. However, invalid attempts that lead to the block do count
    towards the 20-attempt limit.
  </Accordion>

  <Accordion title="Can I get permanently banned for too many invalid attempts?">
    Repeated and excessive attempts to bypass the security block may lead to a permanent ban of the API key or even the associated workspace. We recommend resolving the underlying issue rather than repeatedly hitting the block.
  </Accordion>
</AccordionGroup>

## Need Help?

If you're having trouble with API key blocks:

<CardGroup cols={2}>
  <Card title="Contact Support" icon="life-ring" href="mailto:team@getsnippets.ai">
    Get help from our team
  </Card>
</CardGroup>
