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

# Channel Affinity Guide

> Keep sessions on the same upstream channel to help reuse prompt caches.

Within a conversation, MixRoute tries to send requests to the same upstream channel instead of picking a new channel each time.

This helps with **prompt caching**. Upstream providers typically scope their caches to an account or API key. If requests switch channels mid-conversation, they may not be able to reuse the earlier cache. Keeping the channel stable improves the chance of a cache hit, particularly for long conversations and coding workflows.

## Which requests qualify?

This table describes channel affinity. GPT models can also use prompt caching through Chat Completions, as shown below.

| Model | Endpoint | Session identifier |
| - | - | - |
| Starts with `gpt-` | `/v1/responses` | `prompt_cache_key` in the request body |
| Starts with `claude-` | `/v1/messages` | `metadata.user_id` in the request body |
| Starts with `gemini-` | `/v1/chat/completions` | `X-Session-Id` request header |
| Starts with `gemini-` | `/v1/models/{model}:generateContent` and `/v1beta/models/{model}:generateContent`, including their `:streamGenerateContent` variants | `X-Session-Id` request header |

Requests that do not meet these conditions follow the usual routing rules.

## Request examples

Set `MIXROUTE_API_KEY` before running these examples. Use a model available to the group associated with your API key.

### Example 1: Codex / GPT (`/v1/responses`)

MixRoute identifies the session using `prompt_cache_key` in the body. **Keep the same value for every request within the session.**

```bash theme={null}
curl https://api.mixroute.ai/v1/responses \
  -H "Authorization: Bearer $MIXROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6.2-astra",
    "prompt_cache_key": "my-project-session-001",
    "input": [
      {
        "role": "user",
        "content": "Please identify performance issues in the following code..."
      }
    ]
  }'
```

For the second turn, keep `prompt_cache_key` unchanged and append the new content to `input`:

```bash theme={null}
curl https://api.mixroute.ai/v1/responses \
  -H "Authorization: Bearer $MIXROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6.2-astra",
    "prompt_cache_key": "my-project-session-001",
    "input": [
      { "role": "user", "content": "Please identify performance issues in the following code..." },
      { "role": "assistant", "content": "...the previous answer..." },
      { "role": "user", "content": "How can I optimize the loop?" }
    ]
  }'
```

### Example 2: GPT (`/v1/chat/completions`)

Put fixed instructions or reference material at the start of `messages` and put the question that changes each turn at the end. Keep the prefix unchanged on later requests. `prompt_cache_key` is an optional cache grouping key. If you use it, keep it the same for requests in the group that share a prefix.

```bash theme={null}
curl https://api.mixroute.ai/v1/chat/completions \
  -H "Authorization: Bearer $MIXROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6.2-astra",
    "prompt_cache_key": "my-project-session-001",
    "messages": [
      { "role": "developer", "content": "You are a code reviewer. Put your stable project guidelines here." },
      { "role": "user", "content": "How can I reduce repeated work inside a loop?" }
    ]
  }'
```

This short example illustrates the request format only. Under [OpenAI's prompt caching rules](https://developers.openai.com/api/docs/guides/prompt-caching), GPT 6.2 Astra requires a cacheable prefix of at least 1,024 tokens. After reusing a sufficiently long prefix, check whether `usage.prompt_tokens_details.cached_tokens` is greater than 0.

### Example 3: Claude (`/v1/messages`)

MixRoute identifies the session using `metadata.user_id` in the body. **Keep it unchanged within the session.**

```bash theme={null}
curl https://api.mixroute.ai/v1/messages \
  -H "x-api-key: $MIXROUTE_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "metadata": {
      "user_id": "my-project-session-001"
    },
    "system": [
      {
        "type": "text",
        "text": "You are a senior code reviewer... (a longer, fixed system prompt)",
        "cache_control": { "type": "ephemeral" }
      }
    ],
    "messages": [
      { "role": "user", "content": "Please review this code..." }
    ]
  }'
```

> Affinity helps send requests to the same channel. It does not create the upstream cache. Claude supports `cache_control` under its upstream cache rules, and the example adds an explicit cache marker.

### Example 4: Gemini (native and OpenAI-compatible APIs)

Both APIs use the `X-Session-Id` request header to identify the session. Reuse the same value for each request in that session. Choose either API format below.

**Gemini native API**

```bash theme={null}
curl 'https://api.mixroute.ai/v1beta/models/gemini-3.8-flash:generateContent' \
  -H "Authorization: Bearer $MIXROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Session-Id: my-project-session-001" \
  -d '{
    "systemInstruction": { "parts": [{ "text": "You are a code reviewer." }] },
    "contents": [{ "role": "user", "parts": [{ "text": "How can I reduce repeated work inside a loop?" }] }]
  }'
```

**OpenAI-compatible API (`/v1/chat/completions`)**

```bash theme={null}
curl https://api.mixroute.ai/v1/chat/completions \
  -H "Authorization: Bearer $MIXROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Session-Id: my-project-session-001" \
  -d '{
    "model": "gemini-3.8-flash",
    "messages": [
      { "role": "system", "content": "You are a code reviewer." },
      { "role": "user", "content": "How can I reduce repeated work inside a loop?" }
    ]
  }'
```

The minimum input prefix length for implicit caching varies by model. For Gemini 3.8 Flash, [the threshold is 6,144 tokens](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview#limits). These short examples only illustrate the request format.

### Python example (official OpenAI SDK)

```python theme={null}
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.mixroute.ai/v1",
    api_key=os.environ["MIXROUTE_API_KEY"],
)

SESSION_KEY = "my-project-session-001"  # Keep this value fixed within the session

resp = client.responses.create(
    model="gpt-6.2-astra",
    input="Please identify performance issues in the following code...",
    prompt_cache_key=SESSION_KEY,
)
print(resp.output_text)
```

### Python example (official Anthropic SDK)

```python theme={null}
import os
import anthropic

client = anthropic.Anthropic(
    base_url="https://api.mixroute.ai",
    api_key=os.environ["MIXROUTE_API_KEY"],
)

SESSION_KEY = "my-project-session-001"  # Keep this value fixed within the session

msg = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    metadata={"user_id": SESSION_KEY},
    messages=[{"role": "user", "content": "Please review this code..."}],
)
print(msg.content[0].text)
```

## How to check for cache hits

Inspect the usage fields in the response:

* **Responses**: `usage.input_tokens_details.cached_tokens` greater than 0 indicates a cache hit.
* **Messages**: `usage.cache_read_input_tokens` greater than 0 indicates a cache hit.
* **Chat Completions**: When the response includes `usage.prompt_tokens_details.cached_tokens`, a value greater than 0 indicates a cache hit.
* **Gemini native API**: `usageMetadata.cachedContentTokenCount` greater than 0 indicates a cache hit.

The first request typically does not read from the cache. Later requests may hit it if the session identifier and prefix stay the same and the request meets the model's cache requirements.

## Common mistakes

| Mistake | What happens | What to do instead |
| - | - | - |
| Generate a new UUID for `prompt_cache_key` on every request | Each request is treated as a new session and does not retain the channel | Use one stable value per session |
| Set `metadata.user_id` to the current timestamp | Same as above | Use a session or project ID |
| Put Gemini's `X-Session-Id` in the body | MixRoute does not read it there | Put it in the request header |
| Reuse one identifier across different sessions | The sessions may use the same channel and concentrate load | Use a distinct identifier for each session |

## FAQ

**Q1: Why do my requests keep going to the same channel?**

Once MixRoute selects a channel, subsequent requests with the same session identifier will try to reuse it. A new session may go to another channel.

**Q2: Do different groups or rules share a binding?**

By default, session bindings are separate across groups and routing rules.

**Q3: Why does a channel error not cause a retry on a different channel?**

By default, if the bound channel fails, MixRoute returns the error rather than automatically switching channels. A new channel may not be able to reuse the original cache.

1. Retry shortly afterward in case the upstream problem is temporary.
2. If the error persists, start a new session. A new identifier causes MixRoute to select a channel again.
3. If the problem continues, contact support with the time and request ID.

**Q4: Why is my cache hit rate low?**

* The session identifier changes between requests, so MixRoute cannot recognize the same session and keep the channel stable.
* The prompt prefix changes between requests, such as when a timestamp is inserted at the start.
* A new session does not yet have any cached content.
* The channel binding may have expired after a long pause.

**Q5: How do I use affinity in my own script?**

Use the session identifier shown in the request example for your API. Use a different identifier for each session and keep it unchanged within that session.

**Q6: Does this change my billing?**

Affinity does not change billing rules. Cache read and write rates follow MixRoute pricing.

**Q7: How do I prevent one request from being bound to a channel?**

Omit the relevant session identifier if your workflow allows it. A new identifier selects a channel again but does not disable affinity. Contact MixRoute support to disable affinity entirely.

## Summary

* Affinity covers eligible GPT Responses, Claude Messages, native Gemini, and Gemini on Chat Completions requests.
* Keeping a session on the same channel helps it reuse prompt caches.
* MixRoute does not switch channels automatically after a bound-channel error by default. Retry shortly afterward or start a new session.
* When writing your own script, keep the session identifier stable.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.