---
title: Prompt Cache Misses With Stored Messages
description: How to fix prompt cache misses that appear when the conversation history is loaded from a database that does not keep the key order of JSON objects.
url: "https://ai-sdk.dev/docs/troubleshooting/prompt-cache-misses-with-stored-messages"
docs_index: /llms.txt
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

## Issue

Your application stores the messages of each turn in a database and loads them as the history of the next turn.
Prompt caching works between the steps of one turn, but the first request of the next turn reads fewer tokens from the cache than you expect when the previous turn had tool calls.
You can see this in `usage.inputTokenDetails.cacheReadTokens`. No error is thrown.

## Cause

Providers such as OpenAI and Anthropic only read from the prompt cache when the start of a request is identical to an earlier request.
When the same data is sent as different text, the cache is missed from the first difference on.

Tool call inputs and JSON tool results are objects, and some stores do not keep the order of object keys:

- Postgres `jsonb` "does not preserve the order of object keys" ([PostgreSQL documentation](https://www.postgresql.org/docs/current/datatype-json.html)).
- A DynamoDB map is "an unordered collection of name-value pairs" ([DynamoDB documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.Document.Map)).

After a round trip through such a store, a tool call or tool result can come back with its keys in another order.
The AI SDK sends the messages that you pass with the key order that they have, so the request text changes.
For example, in a request to the OpenAI Responses API:

```text
turn 1: "arguments":"{\"query\":\"stackable mugs\",\"limit\":2}"
turn 2: "arguments":"{\"limit\":2,\"query\":\"stackable mugs\"}"
```

The messages are equal as data, which makes this hard to find: comparing them shows no difference, and most tracing tools display them as equal.

## Solution

### 1. Store messages in a type that keeps the key order

Use a column or attribute type that stores the JSON text as it was written.
In Postgres, use `json` or `text` instead of `jsonb`.
In DynamoDB, store the serialized message as a string instead of a map.

This is the preferred solution, because the model receives the same messages as before.
If you need `jsonb`, for example to index or query the stored messages, use the second solution.

### 2. Sort the keys before the request is sent

If you cannot change how the messages are stored, sort the keys of tool call inputs and JSON tool results in a [language model middleware](/docs/ai-sdk-core/middleware).
The request text is then the same for every key order that the stored messages have:

```ts title="sort-tool-json-keys-middleware.ts"
import type { LanguageModelMiddleware } from 'ai';

function sortKeys<T>(value: T): T {
  if (Array.isArray(value)) {
    return value.map(sortKeys) as T;
  }

  if (value === null || typeof value !== 'object') {
    return value;
  }

  return Object.fromEntries(
    Object.keys(value)
      .sort()
      .map(key => [key, sortKeys((value as Record<string, unknown>)[key])]),
  ) as T;
}

export function sortToolJsonKeysMiddleware(): LanguageModelMiddleware {
  return {
    specificationVersion: 'v4',
    transformParams: async ({ params }) => ({
      ...params,
      prompt: params.prompt.map(message => {
        if (message.role === 'assistant') {
          return {
            ...message,
            content: message.content.map(part =>
              part.type === 'tool-call' && typeof part.input === 'object'
                ? { ...part, input: sortKeys(part.input) }
                : part,
            ),
          };
        }

        if (message.role === 'tool') {
          return {
            ...message,
            content: message.content.map(part =>
              part.type === 'tool-result' &&
              (part.output.type === 'json' || part.output.type === 'error-json')
                ? {
                    ...part,
                    output: {
                      ...part.output,
                      value: sortKeys(part.output.value),
                    },
                  }
                : part,
            ),
          };
        }

        return message;
      }),
    }),
  };
}
```

Wrap your model with the middleware:

```ts
import { openai } from '@ai-sdk/openai';
import { wrapLanguageModel } from 'ai';
import { sortToolJsonKeysMiddleware } from './sort-tool-json-keys-middleware';

const model = wrapLanguageModel({
  model: openai('gpt-6-luna'),
  middleware: sortToolJsonKeysMiddleware(),
});
```

Sorting changes the key order that the model sees in its earlier tool calls,
and models can repeat that order when they write later tool calls. If the
input schema of a tool depends on key order, for example a `reasoning`
property that the model should write before the other properties, change the
storage type instead. See the [measurements in the GitHub
issue](https://github.com/vercel/ai/issues/25698#issuecomment-7360200729).

Conversations that are in progress when you add the middleware miss the cache once, because their earlier requests were sent with the unsorted keys.

## Finding where the prompt changes

To confirm that key order is the cause, compare the last request of one turn with the first request of the next turn.
The `include` option keeps the request body of each step in the result:

```ts
import { generateText, stepCountIs } from 'ai';

const result = await generateText({
  model,
  tools,
  messages,
  stopWhen: stepCountIs(5),
  include: { requestBody: true },
});

// the first and the last request that this turn sent to the provider
const firstRequestBody = result.steps[0]?.request.body;
const lastRequestBody = result.steps.at(-1)?.request.body;
```

Keep `lastRequestBody` until the next turn, and compare it with the `firstRequestBody` of that turn:

```ts
// Returns the text around the first character where two request bodies differ.
function firstDifference(previous: unknown, next: unknown) {
  const a = JSON.stringify(previous) ?? '';
  const b = JSON.stringify(next) ?? '';

  let index = 0;
  while (index < a.length && a[index] === b[index]) {
    index++;
  }

  return {
    previous: a.slice(Math.max(0, index - 40), index + 60),
    next: b.slice(Math.max(0, index - 40), index + 60),
  };
}

console.log(firstDifference(lastRequestBodyOfPreviousTurn, firstRequestBody));
```

When the history is intact, the two request bodies first differ where the new messages of the turn begin.
When the key order has changed, they first differ inside a tool call or tool result of the previous turn, as in the example above.

## Learn more

This behavior and the tradeoffs of sorting keys are discussed in [GitHub issue #25698](https://github.com/vercel/ai/issues/25698), which includes a runnable reproduction.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)