Skip to content
All guides

Caching

Reduce inference costs with exact caching

Enable exact response caching with supported SDK headers, inspect cache metadata, and choose safe request boundaries.

Intermediate6 minNirmosUpdated Oct 25, 2026
On this page

Exact caching can reuse a previously generated response for a matching request without calling the AI provider again. It is useful for repeated classification or extraction requests when reusing an earlier answer is acceptable. A low temperature does not itself guarantee identical model output.

Prepare your integration

Complete the SDK quickstart: create an account and organization, configure a provider credential, and create a personal or service API key in the dashboard. The key needs gateway:execute, cache:read, and cache:write. Select an enabled chat model that your provider credential can use.

The deployment needs working Redis response caching. Cache misses, including storage failures, can still call the provider and incur charges. Streaming and embedding requests do not use this response cache. Semantic response caching is not implemented.

Enable exact caching

Install @nirmos/sdk and save this server-side example as exact-cache.mjs. Set NIRMOS_API_KEY and replace the provider/model placeholder with your configured selection. Optional API and runtime environment variables select another deployment, as described in client configuration.

exact-cache.mjs
import { Nirmos } from "@nirmos/sdk";

const key = process.env.NIRMOS_API_KEY;
if (!key) throw new Error("Set NIRMOS_API_KEY on your server.");
const nirmos = new Nirmos({
  auth: { type: "api-key", key },
  apiBaseUrl: process.env.NIRMOS_API_URL,
  runtimeBaseUrl: process.env.NIRMOS_RUNTIME_URL,
});

for (let attempt = 0; attempt < 2; attempt++) {
  const completion = await nirmos.gateway.chat.create({
    model: "<provider-slug>/<model-slug>",
    temperature: 0,
    maxOutputTokens: 20,
    messages: [{
      role: "user",
      content: "Classify this public example as positive or negative: Great service.",
    }],
  }, {
    headers: {
      "Nirmos-Cache-Mode": "exact",
      "Nirmos-Cache-TTL": "1800",
      "Nirmos-Cache-Scope": "user",
      "Nirmos-Cache-Namespace": "classification-v1",
    },
  });
  console.log(completion.outputText);
  console.log(completion.metadata.cache);
}

Run node exact-cache.mjs. The second identical request can hit the cache when the first response was stored and remains valid. Inspect the returned status rather than assuming a hit.

The headers belong in the second argument, RequestOptions.headers. There is no cache field on ChatCreateParams. TTL is expressed as a positive integer number of seconds, so 1800 means 30 minutes; "30m" is not supported. Explicit exact mode enables caching even when the deployment's global cache default is off.

Choose the sharing boundary

The cache key includes organization, scope, namespace, selected model/provider, request content, generation parameters, and route identity when used. Changing the prompt content or tool schema changes request identity. Provider credential rotation alone does not invalidate responses.

user scope isolates entries by the authenticated user or, for service identities, the API key. It does not isolate individual end customers sharing one service key. tenant scope permits reuse within the organization. Do not treat arbitrary HTTP attribution headers as cache isolation or authorization controls.

Use a distinct namespace when your application needs a new cache generation, and keep customer-specific or authorization-sensitive responses out of shared cache traffic. Avoid relying on request-body metadata to partition cache entries; the current chat adapter does not carry it into cache identity.

Read the result

The SDK exposes optional completion.metadata.cache fields:

FieldMeaning
statusCache decision reported by runtime, such as Hit or Miss
layerReported cache layer
remainingTtlSecondsRemaining lifetime reported for the response

Cache status differs from completion.usage.cachedTokens, which represents provider-reported cached input tokens. The SDK does not expose every raw cache response header as a metadata field. Use logs and traces for available operational records; persistence and payload retention depend on deployment configuration.

Bypass or replace cached responses

Use Nirmos-Cache-No-Store: true to skip both reads and writes for a request. Nirmos-Cache-Refresh: true skips the read and permits a replacement write. Nirmos-Cache-Invalidate: true deletes the matching request entry before execution and requires cache:invalidate; subsequent execution can write again when allowed.

These controls apply to matching requests. There is no public tag-based invalidation endpoint. TTL controls ordinary cache freshness, not an organization-wide deletion policy. Keep prompt content caching, which is local to the SDK client, separate from gateway response caching.

Last updated Oct 25, 2026 by Nirmos

Continue building

Apply this guide to a production Nirmos project.

Use the reference documentation for complete request fields, routing policy, and environment configuration.