fix(cache): skip embeddings in the response cache

Embeddings responses are large and rarely repeat. Each one was stored
for the cache TTL in the shared Redis. A burst of them raised memory
on the shared Dragonfly to its limit.

The cache now skips /v1/embeddings unless cache.cacheEmbeddings is
true. The default is false. Chat caching does not change.
This commit is contained in:
2026-10-28 20:34:48 +00:00
parent 52b5e60719
commit 6d3c8bf9b7
5 changed files with 94 additions and 3 deletions
+3 -1
View File
@@ -545,6 +545,7 @@ byte-identically to before multi-group support existed.
| `ttl` | `string` (Go duration) | `5m` | How long a cached response stays valid. A malformed duration string is a construction error. Zero or negative is accepted, not refused — construction logs one warning, since the store floors it to a 1-second TTL rather than actually disabling the cache; set `enabled: false` to turn caching off. | | `ttl` | `string` (Go duration) | `5m` | How long a cached response stays valid. A malformed duration string is a construction error. Zero or negative is accepted, not refused — construction logs one warning, since the store floors it to a 1-second TTL rather than actually disabling the cache; set `enabled: false` to turn caching off. |
| `maxBodyBytes` | `int` | `1048576` (1MiB) | Largest response body still eligible for caching; a larger one is skipped (never stored, never an error). Maximum accepted value is `8388608` (8MiB) — above that is a construction error. | | `maxBodyBytes` | `int` | `1048576` (1MiB) | Largest response body still eligible for caching; a larger one is skipped (never stored, never an error). Maximum accepted value is `8388608` (8MiB) — above that is a construction error. |
| `accountHits` | `bool` | `false` | When `true`, a cache hit adds the usage stored with the cached response to the requesting user's and group's token and cost counters, so budgets also bind repeated identical prompts. `false` counts a hit as a request only. | | `accountHits` | `bool` | `false` | When `true`, a cache hit adds the usage stored with the cached response to the requesting user's and group's token and cost counters, so budgets also bind repeated identical prompts. `false` counts a hit as a request only. |
| `cacheEmbeddings` | `bool` | `false` | When `true`, `/v1/embeddings` responses are cached too. `false`: embeddings always go upstream and are never stored, because vector bodies are large and rarely repeat. Chat caching is unaffected. |
### `BreakerConfig` ### `BreakerConfig`
@@ -1438,7 +1439,8 @@ disabled with one warning logged at construction, never a per-replica
in-process fallback: divergent replicas would otherwise serve different in-process fallback: divergent replicas would otherwise serve different
cached bodies for the same request. cached bodies for the same request.
- **What's cacheable**: a non-streaming request to either route, whose - **What's cacheable**: a non-streaming chat request, or a non-streaming
embeddings request when `cache.cacheEmbeddings` is `true`, whose
upstream response was HTTP 200 and no larger than `cache.maxBodyBytes`. upstream response was HTTP 200 and no larger than `cache.maxBodyBytes`.
Never cached: a streaming request, native passthrough, MCP/A2A, the Never cached: a streaming request, native passthrough, MCP/A2A, the
image/audio endpoints (see [Image and audio endpoints](#image-and-audio-endpoints)), image/audio endpoints (see [Image and audio endpoints](#image-and-audio-endpoints)),
+4 -1
View File
@@ -115,7 +115,9 @@ func buildResponseCache(cc CacheConfig, client *respClient, logf, warnf, errorf
logf("cache: enabled but redis is not configured; response caching disabled") logf("cache: enabled but redis is not configured; response caching disabled")
return nil, nil return nil, nil
} }
return newResponseCache(client, ttl, maxBody, logf, errorf), nil c := newResponseCache(client, ttl, maxBody, logf, errorf)
c.embeddings = cc.CacheEmbeddings
return c, nil
} }
// groupCacheEnabled resolves whether grp's requests are cacheable, given // groupCacheEnabled resolves whether grp's requests are cacheable, given
@@ -229,6 +231,7 @@ type responseCache struct {
lastFailure time.Time lastFailure time.Time
ttl time.Duration ttl time.Duration
maxBodyBytes int maxBodyBytes int
embeddings bool // CacheConfig.CacheEmbeddings
logMu sync.Mutex logMu sync.Mutex
} }
+4
View File
@@ -473,6 +473,10 @@ type CacheConfig struct {
// budgets also bind repeated identical prompts. Defaults to false: a // budgets also bind repeated identical prompts. Defaults to false: a
// hit then adds only to the request counters. // hit then adds only to the request counters.
AccountHits bool `json:"accountHits,omitempty"` AccountHits bool `json:"accountHits,omitempty"`
// CacheEmbeddings opts /v1/embeddings responses into the cache. Off by
// default: a vector body is large and rarely repeats, so it fills the
// shared Redis for little benefit.
CacheEmbeddings bool `json:"cacheEmbeddings,omitempty"`
} }
// BreakerConfig configures the per-provider discovery circuit breaker // BreakerConfig configures the per-provider discovery circuit breaker
+2 -1
View File
@@ -314,7 +314,8 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
// depends only on req["stream"]/grp, neither of which a failover // depends only on req["stream"]/grp, neither of which a failover
// attempt changes. // attempt changes.
streaming, _ := req["stream"].(bool) streaming, _ := req["stream"].(bool)
cacheable := !streaming && g.cache != nil && groupCacheEnabled(grp) cacheable := !streaming && g.cache != nil && groupCacheEnabled(grp) &&
(endpoint != cacheEndpointEmbeddings || g.cache.embeddings)
// pristineReq is the client's own decoded request, snapshotted ONCE, // pristineReq is the client's own decoded request, snapshotted ONCE,
// BEFORE any candidate's adapter ever touches it, with "model" // BEFORE any candidate's adapter ever touches it, with "model"
+81
View File
@@ -1569,6 +1569,87 @@ func TestHandleChat_CacheHitMiss_EndToEnd_CountersAndHeaders(t *testing.T) {
} }
} }
// postEmbeddingsTwice sends the same /v1/embeddings request twice through gw
// and returns both X-Llmgw-Cache headers.
func postEmbeddingsTwice(t *testing.T, gw *Gateway) (first, second string) {
t.Helper()
body := map[string]any{"model": "gpt-test", "input": "hello"}
var got [2]string
for i := range got {
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/embeddings", "sk-alice", body))
if rec.Code != http.StatusOK {
t.Fatalf("request %d: status = %d, body=%s", i+1, rec.Code, rec.Body.String())
}
got[i] = rec.Header().Get("X-Llmgw-Cache")
}
return got[0], got[1]
}
// TestHandleEmbeddings_CacheOffByDefault_NeverCached pins that a gateway with
// the cache enabled still sends every embeddings request upstream, while chat
// keeps its cache.
func TestHandleEmbeddings_CacheOffByDefault_NeverCached(t *testing.T) {
const respBody = `{"object":"list","data":[{"embedding":[0.1,0.2]}],"model":"gpt-test","usage":{"prompt_tokens":5,"total_tokens":5}}`
var upstreamCalls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamCalls++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(respBody))
}))
defer srv.Close()
gw := newCacheTestGateway(t, srv, nil, defaultCacheMaxBodyBytes)
first, second := postEmbeddingsTwice(t, gw)
if first != "" || second != "" {
t.Errorf("X-Llmgw-Cache = %q then %q, want no header on both (embeddings not cached)", first, second)
}
if upstreamCalls != 2 {
t.Errorf("upstreamCalls = %d, want 2 (every embeddings request goes upstream)", upstreamCalls)
}
}
// TestHandleEmbeddings_CacheEmbeddingsEnabled_HitsOnSecondRequest covers the
// opt-in: with CacheEmbeddings set the second identical request is a hit.
func TestHandleEmbeddings_CacheEmbeddingsEnabled_HitsOnSecondRequest(t *testing.T) {
const respBody = `{"object":"list","data":[{"embedding":[0.1,0.2]}],"model":"gpt-test","usage":{"prompt_tokens":5,"total_tokens":5}}`
var upstreamCalls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamCalls++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(respBody))
}))
defer srv.Close()
gw := newCacheTestGateway(t, srv, nil, defaultCacheMaxBodyBytes)
gw.cache.embeddings = true
first, second := postEmbeddingsTwice(t, gw)
if first != "miss" || second != "hit" {
t.Errorf("X-Llmgw-Cache = %q then %q, want miss then hit", first, second)
}
if upstreamCalls != 1 {
t.Errorf("upstreamCalls = %d, want 1 (second request served from cache)", upstreamCalls)
}
}
// TestBuildResponseCache_CacheEmbeddingsFlag_Propagates checks the config
// field reaches the cache.
func TestBuildResponseCache_CacheEmbeddingsFlag_Propagates(t *testing.T) {
noop := func(string, ...any) {}
client := &respClient{}
for _, want := range []bool{false, true} {
c, err := buildResponseCache(CacheConfig{Enabled: true, CacheEmbeddings: want}, client, noop, noop, noop)
if err != nil || c == nil {
t.Fatalf("buildResponseCache(CacheEmbeddings=%v) = %v, %v", want, c, err)
}
if c.embeddings != want {
t.Errorf("CacheEmbeddings=%v: cache.embeddings = %v", want, c.embeddings)
}
}
}
// TestHandleChat_CacheGroupOptOut_NeverServesFromCache is spec §2's // TestHandleChat_CacheGroupOptOut_NeverServesFromCache is spec §2's
// per-group override: GroupConfig.Cache=false must opt the group out even // per-group override: GroupConfig.Cache=false must opt the group out even
// though the global cache is enabled — every request goes to the // though the global cache is enabled — every request goes to the