> For the complete documentation index, see [llms.txt](https://bluegamma.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bluegamma.io/documentation/integrations/api/rate-limits.md).

# Rate Limits & Best Practices

This guide covers rate limits, caching strategies, and best practices for integrating with the BlueGamma API.

***

### Rate Limits

BlueGamma applies rate limits to ensure fair usage and service reliability.

| Limit               | Value       |
| ------------------- | ----------- |
| Requests per second | 20          |
| Burst allowance     | 50 requests |

The burst allowance lets you make up to 50 requests in a short burst before rate limiting kicks in. After that, requests are throttled to 20 per second.

If you exceed these limits, you'll receive a `429 Too Many Requests` response.

{% hint style="info" %}
**Need higher limits?** Contact us at <support@bluegamma.io> to discuss your requirements.
{% endhint %}

***

### Best Practices

#### 1. Cache Responses

Curve data doesn't change every second. Cache responses to reduce API calls:

```python
from functools import lru_cache
from datetime import datetime

@lru_cache(maxsize=100)
def get_swap_rate(index: str, maturity: str, date: str = None):
    date = date or datetime.now().strftime("%Y-%m-%d")
    response = requests.get(
        "https://api.bluegamma.io/v1/swap_rate",
        params={
            "index": index,
            "start_date": "0D",
            "maturity_date": maturity,
            "fixed_leg_frequency": "6M",
        },
        headers={"x-api-key": API_KEY}
    )
    return response.json()
```

**Recommended cache durations:**

| Data Type                 | Cache Duration           |
| ------------------------- | ------------------------ |
| Swap rates                | 1-5 minutes              |
| Forward curves            | 1-5 minutes              |
| Historical data           | 24 hours or longer       |
| Government yields (US)    | 1-5 minutes              |
| Government yields (other) | 24 hours (updated daily) |

#### 2. Batch Your Requests

Instead of making separate calls for each tenor, use curve endpoints that return multiple data points:

**❌ Inefficient — 8 separate calls:**

```python
maturities = ["1Y", "2Y", "3Y", "5Y", "7Y", "10Y", "20Y", "30Y"]
for maturity in maturities:
    get_swap_rate("SOFR", maturity)  # 8 API calls
```

**✅ Efficient — 1 call:**

```python
get_swap_curve("SOFR")  # Returns all tenors in one call
```

#### 3. Use Appropriate Endpoints

| If you need...         | Use this endpoint  |
| ---------------------- | ------------------ |
| Single swap rate       | `/swap_rate`       |
| Full swap curve        | `/get_swap_curve`  |
| Single forward rate    | `/forward_rate`    |
| Full forward curve     | `/forward_curve`   |
| Single discount factor | `/discount_factor` |
| Full discount curve    | `/discount_curve`  |

#### 4. Handle Errors Gracefully

Implement retry logic with exponential backoff:

```python
import time
import requests

def api_request_with_retry(url, params, max_retries=3):
    headers = {"x-api-key": API_KEY}
    
    for attempt in range(max_retries):
        response = requests.get(url, params=params, headers=headers)
        
        if response.status_code == 200:
            return response.json()
        
        if response.status_code == 429:
            # Rate limited — wait and retry
            wait_time = 2 ** attempt  # 1s, 2s, 4s
            print(f"Rate limited. Waiting {wait_time}s...")
            time.sleep(wait_time)
            continue
        
        if response.status_code >= 500:
            # Server error — retry
            time.sleep(1)
            continue
        
        # Client error — don't retry
        response.raise_for_status()
    
    raise Exception("Max retries exceeded")
```

#### 5. Use Valuation Time for Consistency

When building a model that requires multiple data points, use the same `valuation_time` parameter across all requests to ensure consistency:

```python
valuation_time = "2024-12-15T16:00:00"

swap_rate = requests.get(
    "https://api.bluegamma.io/v1/swap_rate",
    params={"index": "SOFR", "start_date": "0D", "maturity_date": "5Y",
            "fixed_leg_frequency": "6M", "valuation_time": valuation_time},
    headers=headers
)
discount_factor = requests.get(
    "https://api.bluegamma.io/v1/discount_factor",
    params={"index": "SOFR", "tenor": "5Y", "valuation_time": valuation_time},
    headers=headers
)
gov_yield = requests.get(
    "https://api.bluegamma.io/v1/gov_yield",
    params={"country": "US", "tenor": "5Y", "valuation_time": valuation_time},
    headers=headers
)
```

This ensures all data points are from the same market snapshot.

***

### Common Mistakes to Avoid

| Mistake                                    | Solution                                       |
| ------------------------------------------ | ---------------------------------------------- |
| Calling API in a tight loop                | Batch requests or add delays                   |
| Not caching historical data                | Cache historical queries — they won't change   |
| Fetching full curves when you need 1 point | Use single-point endpoints for one-off queries |
| Not handling 429 responses                 | Implement retry logic with backoff             |

***

### Need Higher Limits?

If your use case requires higher rate limits, we can discuss custom arrangements:

* **Email:** <support@bluegamma.io>
* **Book a call:** [Schedule here](https://app.lemcal.com/@alivohra/website-demo?back=1)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://bluegamma.io/documentation/integrations/api/rate-limits.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
