{
  "schema_version": 2,
  "id": "develop/ai/redisvl/user_guide/how_to_guides/observability",
  "title": "Observe the Semantic Cache with OpenTelemetry",
  "url": "https://redis.io/docs/latest/develop/ai/redisvl/user_guide/how_to_guides/observability/",
  "summary": "",
  "aliases": [
    "/integrate/redisvl/user_guide/how_to_guides/observability"
  ],
  "tags": [],
  "last_updated": "2026-11-19T09:14:02+01:00",
  "page_type": "content",
  "content_hash": "4682c701ef2353f6b2d2584b69df72ca59741fdf2830b0b7b59e1428d95fcd4b",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "RedisVL can report what `SemanticCache` does through [OpenTelemetry](https://opentelemetry.io/): a trace for every lookup that separates embedding time from search time, a hit rate, and the distance of the nearest match on every lookup, hits and misses alike. That last signal is what you need to tune `distance_threshold`.\n\nRedisVL depends only on the OpenTelemetry API. Your application owns the SDK and the exporters, and RedisVL emits nothing until you configure them. With no SDK configured, the instrumentation adds about 11 µs to a lookup that embeds, measured on an Apple M4 Pro.\n\nSee [Cache LLM Responses](https://redis.io/docs/latest/../llmcache) for how to use the cache itself."
    },
    {
      "id": "install",
      "title": "Install",
      "role": "setup",
      "text": "Install RedisVL with the `otel` extra, plus the SDK and an exporter of your choice:\n\n[code example]\n\nUse `opentelemetry-sdk` 1.32.0 or later. RedisVL’s histograms carry bucket advice, and earlier SDK releases drop it on OTLP export (fixed in 1.31.0) or apply only the first histogram’s advice (fixed in 1.32.0)."
    },
    {
      "id": "configure-an-sdk",
      "title": "Configure an SDK",
      "role": "configuration",
      "text": "Set the global tracer and meter providers once, at application start-up. RedisVL picks them up automatically, whether you create the cache before or after; there is nothing RedisVL-specific to call.\n\n[code example]\n\nThe OTLP exporters send to `http://localhost:4318` unless you set `OTEL_EXPORTER_OTLP_ENDPOINT`, so run an OpenTelemetry Collector there, or point them at a backend that accepts OTLP. With nothing listening, the exporters log connection errors and retry, which can delay shutdown, but your application keeps working.\n\nAll RedisVL telemetry uses the instrumentation scope `redisvl`, with RedisVL’s version and the semantic-conventions schema URL it targets."
    },
    {
      "id": "what-redisvl-emits",
      "title": "What RedisVL emits",
      "role": "content",
      "text": ""
    },
    {
      "id": "spans",
      "title": "Spans",
      "role": "content",
      "text": "Each `check`, `store`, `update` and `drop` call produces a span tree. A lookup looks like this:\n\n[code example]\n\n`store`, `update` and `drop` produce `semantic_cache.store`, `semantic_cache.update` and `semantic_cache.drop`, and async methods produce the same trees as their sync forms. There is an embeddings span only when the operation embeds a prompt: a `check` or `store` given a precomputed `vector` has none, and `update` and `drop` never embed. The embeddings span comes from the vectorizer, so `SemanticRouter`, `SemanticMessageHistory` and direct calls to `embed` and `embed_many` produce it too.\n\n| Span                 | Attribute                                     | Value                                                                                                                                                              |\n|----------------------|-----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `semantic_cache.*`   | `redisvl.cache.name`                          | The cache name                                                                                                                                                     |\n|                      | `redisvl.cache.result`                        | `hit` or `miss`, on `check` only                                                                                                                                   |\n| `embeddings {model}` | `gen_ai.operation.name`                       | `embeddings`                                                                                                                                                       |\n|                      | `gen_ai.provider.name`                        | For example `openai`, `azure.ai.openai`, `cohere`, `mistral_ai`, `gcp.vertex_ai`, `gcp.gemini` or `aws.bedrock`; other vectorizers report their type, such as `hf` |\n|                      | `gen_ai.request.model`                        | The vectorizer’s model                                                                                                                                             |\n|                      | `gen_ai.embeddings.dimension.count`           | The vectorizer’s dimensions, when known                                                                                                                            |\n|                      | `redisvl.embeddings_cache.result`             | `hit`, `miss`, or `partial` for a batch; only when the vectorizer has an `EmbeddingsCache` and the call doesn’t pass `skip_cache=True`                             |\n| `retrieval {index}`  | `gen_ai.operation.name`                       | `retrieval`                                                                                                                                                        |\n|                      | `gen_ai.data_source.id`, `db.collection.name` | The index name                                                                                                                                                     |\n|                      | `gen_ai.retrieval.top_k`                      | `num_results`                                                                                                                                                      |\n|                      | `db.system.name`                              | `redis`                                                                                                                                                            |\n|                      | `db.operation.name`                           | `FT.SEARCH`                                                                                                                                                        |\n|                      | `redisvl.cache.distance_threshold`            | The threshold the lookup used                                                                                                                                      |\n|                      | `redisvl.cache.distance`                      | The nearest candidate’s distance, when there was one                                                                                                               |\n\nA failed operation sets an error status and `error.type` on every RedisVL span it passes through. `error.type` is the exception’s class, prefixed by its module unless it is a builtin, such as `redis.exceptions.ConnectionError`."
    },
    {
      "id": "metrics",
      "title": "Metrics",
      "role": "content",
      "text": "| Metric                                      | Unit   | Attributes                                                                                                      | Recorded on                                                                                                                                        |\n|---------------------------------------------|--------|-----------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|\n| `redisvl.semantic_cache.operation.duration` | `s`    | `redisvl.cache.name`, `redisvl.cache.operation`, `redisvl.cache.result` (on `check`), `error.type` (on failure) | Every `check`, `store`, `update` and `drop`, sync or async                                                                                         |\n| `redisvl.semantic_cache.distance`           | `1`    | `redisvl.cache.name`, `redisvl.cache.result`                                                                    | Every completed lookup that found at least one candidate                                                                                           |\n| `gen_ai.client.operation.duration`          | `s`    | `gen_ai.operation.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `error.type` (on failure)              | Every embedding call that reaches the provider, but not an embeddings-cache hit. One `embed_many` call records one point, covering all its batches |\n\nThere is no counter: the duration histogram’s count is the number of operations. Cache-operation buckets start at 100 µs, because a lookup against local Redis takes about 250 µs before embedding, while embedding-duration buckets follow the GenAI conventions’ advice, from 10 ms. Distance buckets are 0.01 wide up to 0.1, then coarser up to 2, the maximum cosine distance. To change any of them, use an SDK [View](https://opentelemetry.io/docs/languages/python/instrumentation/#metrics).\n\nNames in the `gen_ai.*` namespace follow the OpenTelemetry GenAI conventions, which are still in Development status and may change in a future release."
    },
    {
      "id": "tune-the-distance-threshold",
      "title": "Tune the distance threshold",
      "role": "content",
      "text": "The distance histogram, split by result, shows how close your lookups come to the threshold, which defaults to 0.1:\n\n| Pattern                                 | What it suggests                                  | What to do                                                          |\n|-----------------------------------------|---------------------------------------------------|---------------------------------------------------------------------|\n| Misses bunched just above the threshold | Some may be near-duplicates the cache is refusing | Consider loosening the threshold to turn the genuine ones into hits |\n| Hits bunched just below the threshold   | These are the matches most likely to be wrong     | Consider tightening the threshold, trading hit rate for accuracy    |\n| Misses spread far above the threshold   | Genuinely new prompts                             | Nothing: no threshold would serve them                              |\n\nThe distance of misses, as a heatmap:\n\n[code example]\n\nThe share of misses within 0.05 of a 0.1 threshold:\n\n[code example]\n\nThe share counts only misses that found a candidate: a lookup whose filter excluded every entry, or that ran against an empty cache, records no distance. The `le` value must be one of the bucket boundaries: a value between them, such as `0.23`, returns nothing. The metric does not record which threshold a lookup used, so after you change it, compare windows from before and after rather than mixing them.\n\nA distance cannot tell you whether a match was right. Before you move the threshold, look at the prompts behind those distances with content capture on, as described under [Privacy]()."
    },
    {
      "id": "starter-queries",
      "title": "Starter queries",
      "role": "content",
      "text": "These PromQL queries use the names the OpenTelemetry Prometheus exporter produces. Other pipelines can translate names differently, so check your backend’s metric names first.\n\nHit rate, per cache:\n\n[code example]\n\nThe `or` term reports 0 for a cache that has never hit, which would otherwise drop out of the result because it has no `hit` series. Failed checks carry `error.type` and no result, so they count towards neither side.\n\n95th-percentile duration, per operation:\n\n[code example]\n\n95th-percentile embedding latency, per provider and model:\n\n[code example]"
    },
    {
      "id": "explore-with-a-local-stack",
      "title": "Explore with a local stack",
      "role": "content",
      "text": "The repository includes a Docker Compose stack for trying all of this on your machine, in [`docs/user_guide/how_to_guides/observability-stack`](https://github.com/redis/redis-vl-python/tree/main/docs/user_guide/how_to_guides/observability-stack). It is for local use only: every port listens on `127.0.0.1`, and Grafana lets anyone who reaches it edit and save dashboards without signing in. Saved changes live in the Grafana container, so `docker compose down` discards them; to keep a customised dashboard, use the dashboard’s **Export** > **Export as JSON**.\n\n[code example]\n\nWhen you are done, `docker compose down -v` stops the stack and deletes the metrics it stored.\n\n| Service                 | Address                                             | Role                                                                                       |\n|-------------------------|-----------------------------------------------------|--------------------------------------------------------------------------------------------|\n| Redis 8                 | `localhost:6379`, or `REDIS_PORT` if you set it     | The cache’s database                                                                       |\n| OpenTelemetry Collector | `localhost:4318` (HTTP) and `localhost:4317` (gRPC) | Receives OTLP from your application, and passes metrics to Prometheus and traces to Jaeger |\n| Prometheus              | [http://localhost:9090](http://localhost:9090)      | Stores the metrics                                                                         |\n| Jaeger                  | [http://localhost:16686](http://localhost:16686)    | Stores and shows the traces                                                                |\n| Grafana                 | [http://localhost:3000](http://localhost:3000)      | Opens on the starter dashboard                                                             |\n\nTo fill it, run the [Tune the Semantic Cache with Telemetry](https://redis.io/docs/latest/../semantic_cache_observability) notebook with `OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318` set. Its last cell sends three minutes of lookups.\n\nThe starter dashboard, **RedisVL Semantic Cache**, has four rows:\n\n- **Hit rate**: per cache over the selected range and over time, and lookups per second by result.\n- **Threshold tuning**: heatmaps of the nearest distance on misses and on hits, and two \"what if\" panels. One shows the share of misses a looser threshold would have served, the other the share of hits a tighter one would have refused. Pick the candidate thresholds with the dashboard’s **Looser threshold** and **Tighter threshold** variables, which offer only bucket boundaries.\n- **Latency**: operation and embedding percentiles, and redis-py’s `FT.SEARCH` and `PIPELINE` latency, with the caveats in the next section.\n- **Traces**: links to the service’s recent and slowest lookups in Jaeger.\n\nTo use the dashboard elsewhere, import [`grafana/semantic-cache.json`](https://github.com/redis/redis-vl-python/blob/main/docs/user_guide/how_to_guides/observability-stack/grafana/semantic-cache.json) into your own Grafana, choose your Prometheus data source in its **Metrics** variable, and set **Jaeger URL** to your trace UI. Its queries expect the Collector’s Prometheus exporter names and Prometheus’s `honor_labels: true`, so that `job` is your application’s `service.name`."
    },
    {
      "id": "add-redis-pys-own-metrics",
      "title": "Add redis-py’s own metrics",
      "role": "content",
      "text": "redis-py 7.4 and later ship their own OpenTelemetry metrics for connections and commands. RedisVL never initialises them, so turn them on yourself after setting the meter provider. Command latency is not in the default groups:\n\n[code example]\n\nredis-py emits metrics only, not spans, which is why RedisVL traces the search itself as the `retrieval` span.\n\nCommand latency arrives as `db.client.operation.duration`, labelled with `db.operation.name`. A lookup’s search is `FT.SEARCH`. When the cache has a TTL, a hit’s refresh goes out as one pipeline, recorded as `PIPELINE`, and so does every `store`. Neither carries the cache name, and both include every other search and pipeline the process sends.\n\nredis-py labels its metrics with the older `db.system` attribute, where RedisVL’s spans use `db.system.name`, its replacement in current semantic conventions. Both carry the value `redis`, so match on the name each layer emits when you join them.\n\nIf you also run a provider’s own GenAI instrumentation, such as one for the OpenAI SDK, both can report the same embedding call: expect a nested client span, and a second set of `gen_ai.client.operation.duration` points under that library’s instrumentation scope."
    },
    {
      "id": "privacy-and-content-capture",
      "title": "Privacy and content capture",
      "role": "content",
      "text": "By default RedisVL records no prompt, response, metadata or filter values, in any span, event or metric. It never records exception messages on its spans either, because they can contain prompt text: a failure records only the exception’s class. Cache names and model identifiers are exported, so keep tenant or user ids out of cache names.\n\nTo see what the cache matched, set:\n\n[code example]\n\nWith `SPAN_ONLY` or `SPAN_AND_EVENT`, the `retrieval` span also records:\n\n- `gen_ai.retrieval.query.text`: the prompt, whenever the lookup was passed one, even alongside a vector.\n- `gen_ai.retrieval.documents`: a JSON list of the candidates’ entry ids and scores. Each `score` is the cosine similarity, `1 - distance`, so higher is closer, as the GenAI conventions define a relevance score; the nearest raw distance stays on `redisvl.cache.distance`. Entry ids are unsalted SHA-256 hashes of the stored prompt and filters, so treat them as content too.\n\nRedisVL never records response text, but the variable is process-wide: other GenAI instrumentations that read it may also start recording prompts and responses. Unlike some of them, RedisVL does not treat `true` as a span mode, and needs no stability opt-in. It reads the variable once, on the first cache lookup.\n\nPrompts can contain personal data. Capture content in place rather than copying production traffic elsewhere, send it only to a trace backend approved to hold prompt data, sample to limit the volume, and turn capture off again when you have what you need, which takes a restart."
    },
    {
      "id": "turn-it-off",
      "title": "Turn it off",
      "role": "content",
      "text": "To silence RedisVL’s telemetry while keeping the rest of your application’s, set:\n\n[code example]\n\nOnly `true` (case-insensitive) disables it. RedisVL reads the variable once, the first time it records telemetry, so set it before your application starts."
    }
  ],
  "examples": [
    {
      "id": "install-ex0",
      "language": "bash",
      "code": "pip install \"redisvl[otel]\" \"opentelemetry-sdk>=1.32\" opentelemetry-exporter-otlp-proto-http",
      "section_id": "install"
    },
    {
      "id": "configure-an-sdk-ex0",
      "language": "python",
      "code": "from opentelemetry import metrics, trace\nfrom opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter\nfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter\nfrom opentelemetry.sdk.metrics import MeterProvider\nfrom opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor\n\nfrom redisvl.extensions.cache.llm import SemanticCache\n\ntracer_provider = TracerProvider()\ntracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))\ntrace.set_tracer_provider(tracer_provider)\n\nmetrics.set_meter_provider(\n    MeterProvider(metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])\n)\n\ncache = SemanticCache(name=\"llmcache\", redis_url=\"redis://localhost:6379\")\ncache.store(prompt=\"What is the capital of France?\", response=\"Paris\")\ncache.check(prompt=\"What's the capital of France?\")",
      "section_id": "configure-an-sdk"
    },
    {
      "id": "spans-ex0",
      "language": "default",
      "code": "semantic_cache.check     INTERNAL\n├── embeddings {model}   CLIENT\n└── retrieval {index}    CLIENT",
      "section_id": "spans"
    },
    {
      "id": "tune-the-distance-threshold-ex0",
      "language": "promql",
      "code": "sum by (le) (rate(redisvl_semantic_cache_distance_bucket{redisvl_cache_result=\"miss\"}[1h]))",
      "section_id": "tune-the-distance-threshold"
    },
    {
      "id": "tune-the-distance-threshold-ex1",
      "language": "promql",
      "code": "sum(rate(redisvl_semantic_cache_distance_bucket{redisvl_cache_result=\"miss\", le=\"0.15\"}[1h]))\n/\nsum(rate(redisvl_semantic_cache_distance_count{redisvl_cache_result=\"miss\"}[1h]))",
      "section_id": "tune-the-distance-threshold"
    },
    {
      "id": "starter-queries-ex0",
      "language": "promql",
      "code": "(\n  sum by (redisvl_cache_name) (rate(redisvl_semantic_cache_operation_duration_seconds_count{redisvl_cache_operation=\"check\", redisvl_cache_result=\"hit\"}[5m]))\n  or\n  0 * sum by (redisvl_cache_name) (rate(redisvl_semantic_cache_operation_duration_seconds_count{redisvl_cache_operation=\"check\", redisvl_cache_result=\"miss\"}[5m]))\n)\n/\nsum by (redisvl_cache_name) (rate(redisvl_semantic_cache_operation_duration_seconds_count{redisvl_cache_operation=\"check\", redisvl_cache_result=~\"hit|miss\"}[5m]))",
      "section_id": "starter-queries"
    },
    {
      "id": "starter-queries-ex1",
      "language": "promql",
      "code": "histogram_quantile(0.95, sum by (le, redisvl_cache_operation) (rate(redisvl_semantic_cache_operation_duration_seconds_bucket[5m])))",
      "section_id": "starter-queries"
    },
    {
      "id": "starter-queries-ex2",
      "language": "promql",
      "code": "histogram_quantile(0.95, sum by (le, gen_ai_provider_name, gen_ai_request_model) (rate(gen_ai_client_operation_duration_seconds_bucket{gen_ai_operation_name=\"embeddings\"}[5m])))",
      "section_id": "starter-queries"
    },
    {
      "id": "explore-with-a-local-stack-ex0",
      "language": "bash",
      "code": "cd docs/user_guide/how_to_guides/observability-stack\ndocker compose up -d",
      "section_id": "explore-with-a-local-stack"
    },
    {
      "id": "add-redis-pys-own-metrics-ex0",
      "language": "python",
      "code": "from redis.observability import MetricGroup, OTelConfig, get_observability_instance\n\nget_observability_instance().init(\n    OTelConfig(\n        metric_groups=[\n            MetricGroup.CONNECTION_BASIC,\n            MetricGroup.RESILIENCY,\n            MetricGroup.COMMAND,\n        ]\n    )\n)",
      "section_id": "add-redis-pys-own-metrics"
    },
    {
      "id": "privacy-and-content-capture-ex0",
      "language": "bash",
      "code": "export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY",
      "section_id": "privacy-and-content-capture"
    },
    {
      "id": "turn-it-off-ex0",
      "language": "bash",
      "code": "export REDISVL_OTEL_DISABLED=true",
      "section_id": "turn-it-off"
    }
  ]
}
