← Plugin catalog
Developer Tools
Redis
Redis v1.4.0
Publisher description
From the marketplace listing
Design, implement, review, and troubleshoot Redis applications with focused guidance for data structures, connections, Redis Search, semantic caching, clustering, security, observability, and Iris agent memory.
Language: English · Automatically detected from descriptions.
Files & skills
File archives
Plugin package68 files · 124 KBBrowse files →
Skill instructions
iris-development4.24 KB
--- name: iris-development description: Iris is Redis's umbrella for AI-focused products. Use this skill when integrating with the Iris Redis Agent Memory (RAM) data plane on Redis Cloud — recording session events for an AI agent, creating or searching long-term memories, configuring a memory store, or tuning background memory promotion. Code examples use the official `redis-agent-memory` (Python) and `@redis-iris/agent-memory` (TypeScript) SDKs. license: MIT --- # Iris: Redis Agent Memory **Iris** is the umbrella brand for Redis's AI-focused products. This skill currently covers one product in that family: **Redis Agent Memory (RAM)** — the persistent memory layer for AI agents, delivered as a managed service on Redis Cloud. Additional Iris products will be added as separate sections when they ship. Redis Agent Memory exposes a REST/JSON data-plane API with two memory tiers: - **Session memory** — append-only conversation history per session (working memory). - **Long-term memory** — semantically searchable records extracted from sessions (or created directly). A background **promotion** worker — managed by Redis Cloud — extracts durable facts from session events and writes them into long-term memory. ## Official SDKs All code samples use the official SDKs: | Language | Package | Class | Install | | ---------- | -------------------------- | ------------- | ---------------------------------- | | Python | `redis-agent-memory` | `AgentMemory` | `pip install redis-agent-memory` | | TypeScript | `@redis-iris/agent-memory` | `AgentMemory` | `npm add @redis-iris/agent-memory` | Both SDKs read the bearer token from `AGENT_MEMORY_API_KEY` and the default store ID from `AGENT_MEMORY_STORE_ID`. The production data-plane URL is `https://gcp-us-east4.memory.redis.io`; the exact URL for your service is also shown in the Cloud console after provisioning. ## When to Apply Reference these guidelines when: - Creating a memory service on Redis Cloud ([https://cloud.redis.io/#/agent-memory](https://cloud.redis.io/#/agent-memory)) - Wiring an agent to call `AgentMemory.add_session_event(...)` / `addSessionEvent(...)` - Searching long-term memory with `search_long_term_memory(...)` / `searchLongTermMemory(...)` - Choosing between session events and direct long-term memory writes ## Rule Categories by Priority | Priority | Category | Impact | Prefix | | -------- | ----------------------- | ------ | ------------ | | 1 | Setup & Cloud Service | HIGH | `setup-` | | 2 | Session Memory / Events | HIGH | `session-` | | 3 | Long-Term Memory | HIGH | `ltm-` | | 4 | Memory Promotion | MEDIUM | `promotion-` | ## Quick Reference ### 1. Setup & Cloud Service (HIGH) - [`setup-cloud-service`](references/setup-cloud-service.md) - Create a Memory service on Redis Cloud - [`setup-auth-token`](references/setup-auth-token.md) - Authenticate the SDK with a store API key ### 2. Session Memory / Events (HIGH) - [`session-when-to-use`](references/session-when-to-use.md) - Choose session events vs direct long-term memory - [`session-add-event`](references/session-add-event.md) - Append a session event correctly - [`session-retrieval`](references/session-retrieval.md) - Retrieve session memory and individual events ### 3. Long-Term Memory (HIGH) - [`ltm-bulk-create`](references/ltm-bulk-create.md) - Create long-term memories in bulk with idempotent IDs - [`ltm-search`](references/ltm-search.md) - Search long-term memory semantically with filters - [`ltm-organize`](references/ltm-organize.md) - Organize records with namespace, ownerId, topics, and memoryType ### 4. Memory Promotion (MEDIUM) - [`promotion-overview`](references/promotion-overview.md) - How background promotion works ## How to Use Read individual rule files under `references/` for detailed explanations and code examples: ``` references/setup-cloud-service.md references/session-add-event.md references/promotion-overview.md ``` Each rule file contains: - Brief explanation of why it matters - Correct example(s) with Python and TypeScript SDK code - Either an "Incorrect" example or "When to use / When NOT needed" guidance - Additional context and references
Referenced files: 10
redis-clustering3.99 KB
---
name: redis-clustering
description: Redis Cluster and replication guidance covering hash tags for multi-key operations, avoiding CROSSSLOT errors, and reading from replicas to scale read-heavy workloads. Use when designing keys for a sharded Redis Cluster, debugging CROSSSLOT errors on MGET / SDIFF / pipelines, configuring a multi-key transaction in a cluster, or routing reads to replicas for caches, analytics, or dashboards.
license: MIT
---
# Redis Clustering
Guidance for designing keys and routing reads in a sharded Redis Cluster (and in standalone primary/replica replication). Covers the two failure modes that bite most new cluster users: `CROSSSLOT` errors on multi-key operations, and overloading primaries with read traffic.
## When to apply
- Designing keys for a Redis Cluster deployment.
- Debugging a `CROSSSLOT` error on `MGET`, `SDIFF`, transactions, or pipelines.
- Implementing transactions / Lua scripts that touch multiple keys.
- Scaling out read traffic without adding shards.
## 1. Hash tags for multi-key operations
Redis Cluster distributes keys across 16,384 slots by hashing the key name. Any command that touches **multiple keys** (`MGET`, `SDIFF`, `SUNIONSTORE`, transactions, pipelines, Lua scripts with multiple `KEYS[]`) requires all keys to live on the **same slot** — otherwise the server returns a `CROSSSLOT` error.
Hash tags force this: the part between `{` and `}` is the only thing hashed for slot assignment, so two keys sharing a hash tag always land together.
```python
# Same slot — multi-key ops work
redis.set("{user:1001}:profile", "...")
redis.set("{user:1001}:settings", "...")
redis.lmove("{user:1001}:pending", "{user:1001}:processed", "LEFT", "RIGHT")
```
```python
# Different keys, no hash tag — CROSSSLOT on multi-key commands in cluster mode
redis.set("user:1001:profile", "...")
redis.set("user:1001:settings", "...")
pipe = redis.pipeline()
pipe.get("user:1001:profile")
pipe.get("user:1001:settings")
pipe.execute() # CROSSSLOT error in cluster
```
Rules of thumb:
- **Use a tag scoped to the meaningful entity**, e.g. `{user:1001}`. Avoid bare `{1001}` — unrelated namespaces (`purchase:{1001}`, `employee:{1001}`) would all collide on the same slot.
- **Only tag where you actually need multi-key ops.** Tagging everything creates hotspots and defeats the point of sharding.
- A single-key command on a hash-tagged key works fine, so adding tags later is incremental — but renaming keys in production is painful, so plan tagging up front for entities you'll group.
See [references/hash-tags.md](references/hash-tags.md).
## 2. Read replicas for read-heavy workloads
If reads dominate writes, route them to replicas to free primary capacity. Works both in Redis Cluster (each shard has 1+ replica) and in standalone primary/replica replication.
```python
# Redis Cluster: enable replica reads on the client
from redis.cluster import RedisCluster
rc = RedisCluster(host="localhost", port=6379, read_from_replicas=True)
rc.set("key", "value") # → primary
value = rc.get("key") # → may be served by a replica
```
For non-cluster setups, point two clients at the right nodes:
```python
primary = Redis(host="primary-host", port=6379)
replica = Redis(host="replica-host", port=6379)
primary.set("key", "value")
value = replica.get("key")
```
The trade-off is consistency: **replicas are eventually consistent**. Don't read your own writes from a replica; don't use replica reads for anything that requires strict freshness (financial balances, idempotency state). Good fits: cache layers, analytics, dashboards, recommendation feeds.
See [references/read-replicas.md](references/read-replicas.md).
## References
- [Redis Cluster spec — hash tags](https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/#hash-tags)
- [Redis: multi-key operations in cluster](https://redis.io/docs/latest/operate/rs/databases/durability-ha/clustering/#multikey-operations)
- [Redis: Replication](https://redis.io/docs/latest/operate/oss_and_stack/management/replication/)
Referenced files: 3
redis-connections4.96 KB
---
name: redis-connections
description: Redis client and connection guidance covering connection pooling, multiplexing, pipelining, client-side caching with RESP3, avoiding slow commands (KEYS, SMEMBERS, HGETALL), and tuning socket timeouts. Use when configuring a Redis client (redis-py, Jedis, Lettuce, NRedisStack), batching commands for throughput, eliminating per-request connection creation, iterating large keyspaces with SCAN, enabling client-side caching for read-heavy workloads, or setting connect and read timeouts.
license: MIT
---
# Redis Connections
Client-side guidance for talking to Redis efficiently: how to share connections, how to batch commands, which commands not to call in production, when to turn on client-side caching, and how to set timeouts that fail fast without breaking healthy traffic.
## When to apply
- Creating or reviewing a Redis client setup (redis-py, Jedis, Lettuce, go-redis, NRedisStack).
- Making many small Redis calls and wondering where the latency is going.
- Iterating large keyspaces, sets, hashes, or lists.
- Enabling client-side caching for hot keys.
- Tuning connect / read / write timeouts.
## 1. Pool or multiplex — never one connection per request
The single biggest mistake in Redis client code is opening a new TCP connection for every operation. Always either:
- **Pool** — keep N persistent connections that the application leases per call (redis-py `ConnectionPool`, Jedis `JedisPooled`, go-redis client).
- **Multiplex** — share a single connection across all requests (Lettuce, NRedisStack).
| Style | Used by | Note |
|---|---|---|
| Pool | redis-py, Jedis, go-redis | Each lease blocks if pool exhausted; size the pool to your concurrency |
| Multiplex | Lettuce, NRedisStack | Single connection; **cannot** carry blocking commands like `BLPOP` |
```python
# redis-py — connection pool
pool = redis.ConnectionPool(host="localhost", port=6379, max_connections=50)
r = redis.Redis(connection_pool=pool)
```
See [references/pooling.md](references/pooling.md) for Python + Java + Lettuce examples.
## 2. Pipeline bulk work
For N commands that don't depend on each other's results, send them as a single batch with pipelining. One round-trip instead of N.
```python
pipe = redis.pipeline()
for user_id in user_ids:
pipe.get(f"user:{user_id}")
results = pipe.execute()
```
Use **non-transactional** pipelining for performance, and `pipeline(transaction=True)` only when you actually need atomicity (see redis-core's transactions guidance).
See [references/pipelining.md](references/pipelining.md).
## 3. Avoid commands that scan everything
Anything that walks the whole keyspace (or a whole large container) blocks the server. Use incremental variants instead.
| Don't | Use |
|---|---|
| `KEYS pattern` | `SCAN` cursor loop |
| `SMEMBERS large_set` | `SSCAN` |
| `HGETALL large_hash` | `HSCAN` |
| `LRANGE 0 -1` on a huge list | Paginate (`LRANGE 0 100`) |
```python
cursor = 0
while True:
cursor, keys = redis.scan(cursor, match="user:*", count=100)
for key in keys:
process(key)
if cursor == 0:
break
```
**Blocking commands (`BLPOP`, `BRPOP`, `BLMOVE`) are different** — they intentionally wait for data and are fine for queue consumers, but always pass a timeout, and don't issue them on a multiplexed connection (Lettuce, NRedisStack).
See [references/blocking.md](references/blocking.md).
## 4. Client-side caching for hot keys
For data that's read often and written rarely (config, feature flags, sessions on every request), enable RESP3 client-side caching. The client keeps a local copy and the server invalidates it on writes — saving the round trip for hot reads.
```python
client = redis.Redis(
host="localhost",
port=6379,
protocol=3, # RESP3 is required
cache_config=redis.CacheConfig(max_size=1000),
)
```
Skip it for write-heavy workloads or data that changes constantly — the invalidation traffic overruns the savings.
See [references/client-cache.md](references/client-cache.md).
## 5. Set explicit timeouts
Defaults vary by client and may be too generous. Pick values that match the *application's* failure model:
```python
r = redis.Redis(
host="localhost",
socket_connect_timeout=2.0, # fail fast on dead nodes
socket_timeout=5.0, # tune to expected operation time
retry_on_timeout=True,
)
```
Rule of thumb: connect timeout shorter than read/write timeout. Tight timeouts + retry-on-timeout for latency-sensitive paths; longer timeouts for batch jobs.
See [references/timeouts.md](references/timeouts.md).
## References
- [Redis: Connection Pools and Multiplexing](https://redis.io/docs/latest/develop/clients/pools-and-muxing/)
- [Redis: Pipelining](https://redis.io/docs/latest/develop/use/pipelining/)
- [Redis: SCAN](https://redis.io/docs/latest/commands/scan/)
- [Redis: Client-side caching](https://redis.io/docs/latest/develop/clients/client-side-caching/)
- [Redis: Clients](https://redis.io/docs/latest/develop/clients/)
Referenced files: 6
redis-core2.92 KB
---
name: redis-core
description: Core Redis modeling guidance — choose the right data structure (String, Hash, List, Set, Sorted Set, JSON, Stream, Vector Set) and use consistent colon-separated key names. Use when designing a Redis data model, caching objects, deciding between Hash and JSON, building counters, leaderboards, membership sets, or session stores, or when reviewing/cleaning up Redis key naming.
license: MIT
---
# Redis Core
Foundational guidance for modeling data in Redis. Covers data-type selection and key-name conventions — the two decisions that most directly drive memory, performance, and maintainability.
## When to apply
- Caching objects, sessions, or per-user state.
- Counters, leaderboards, recent-items lists, unique-membership sets.
- Reviewing or refactoring Redis key names.
- Deciding between a Redis Hash and a JSON document for an entity.
## 1. Choose the right data structure
Pick the type that matches the *access pattern*, not just the shape of the data.
| Use case | Recommended type | Why |
|---|---|---|
| Simple values, counters | String | Atomic `INCR`/`DECR`, `SET`/`GET` |
| Object with independently updated fields | Hash | Per-field reads/writes, no whole-object rewrite |
| Queue, recent-N items | List | O(1) push/pop at ends |
| Unique items, membership checks | Set | O(1) `SADD`/`SISMEMBER`/`SCARD` |
| Rankings, score-based ranges | Sorted Set | Score-ordered; `ZADD`/`ZRANGE`/`ZRANK` |
| Nested / hierarchical data | JSON | Path-level updates, nested arrays, RQE indexing |
| Event log, fan-out messaging | Stream | Persistent, consumer groups |
| Vector similarity | Vector Set | Native vector storage with HNSW |
**Common anti-pattern:** stuffing a flat object into a serialized string. Updating one field means fetch + parse + mutate + rewrite. Use a Hash instead.
See [references/choose-data-structure.md](references/choose-data-structure.md) for full rationale and Python/Java examples.
## 2. Use consistent key names
Use `colon-separated` segments with a stable hierarchy:
```
{entity}:{id}:{attribute}
user:1001:profile
user:1001:settings
order:2024:items
session:abc123
article:987:likes
game:space-invaders:leaderboard
```
Rules of thumb:
- **Lowercase, colon-separated.** No spaces, no mixed casing (`User_1001_Profile` is bad).
- **Keep keys short but readable** — keys live in memory and appear in every command.
- **Don't use full URLs or long strings as keys.** Extract a short identifier, or use a hash digest of the URL.
- **Prefix for multi-tenancy** (`tenant:42:user:7:cart`) so scans and ACLs can target a tenant cleanly.
- **Be consistent.** Pick one convention per service and apply it across all keys.
See [references/key-naming.md](references/key-naming.md) for cleanup examples and edge cases.
## References
- [Redis: Choosing the right data type](https://redis.io/docs/latest/develop/data-types/compare-data-types/)
- [Redis: Keys](https://redis.io/docs/latest/develop/use/keyspace/)
Referenced files: 3
redis-observability3.51 KB
---
name: redis-observability
description: Redis observability guidance — which metrics to monitor (memory, connections, hit ratio, ops/sec, rejected connections), which built-in commands to reach for during incident triage (SLOWLOG, INFO, MEMORY DOCTOR, CLIENT LIST, FT.PROFILE), and when to use the Redis Insight GUI. Use when setting up monitoring or alerts for a Redis instance, diagnosing a performance regression, profiling a slow FT.SEARCH query, or wiring Redis metrics into Prometheus, Datadog, or similar.
license: MIT
---
# Redis Observability
What to watch, what to run, and what to alert on. Covers the metrics every Redis deployment should monitor and the built-in commands for ad-hoc diagnosis.
## When to apply
- Setting up monitoring or alerts for a Redis instance.
- Diagnosing a Redis performance regression (high latency, memory pressure, connection storms).
- Profiling a slow `FT.SEARCH` or pipeline.
- Wiring Redis metrics into Prometheus, Datadog, CloudWatch, or similar.
## 1. Monitor these metrics
These come from `INFO` and should be exported to your monitoring system.
| Metric | What it tells you | Alert when |
|---|---|---|
| `used_memory` | Current memory usage | > 80% of `maxmemory` |
| `connected_clients` | Open connections | Sudden spikes or drops |
| `blocked_clients` | Clients waiting on blocking ops | > 0 sustained |
| `instantaneous_ops_per_sec` | Current throughput | Significant drops |
| `keyspace_hits` / `keyspace_misses` | Cache hit ratio | Hit ratio < 80% |
| `rejected_connections` | Hit `maxclients` cap | > 0 |
| `rdb_last_save_time` | Last persistence snapshot | Too old vs. RPO |
```python
info = redis.info()
hit_ratio = info["keyspace_hits"] / max(1, info["keyspace_hits"] + info["keyspace_misses"])
print(f"Memory: {info['used_memory_human']}")
print(f"Clients: {info['connected_clients']}")
print(f"Ops/sec: {info['instantaneous_ops_per_sec']}")
print(f"Hit ratio: {hit_ratio:.1%}")
```
See [references/metrics.md](references/metrics.md).
## 2. Built-in commands for debugging
Reach for these when something looks off.
| Topic | Command |
|---|---|
| Slow commands | `SLOWLOG GET 10` / `SLOWLOG LEN` / `SLOWLOG RESET` |
| Server snapshot | `INFO all` (or `INFO memory` / `INFO stats` / `INFO clients` / `INFO replication`) |
| Memory diagnostics | `MEMORY DOCTOR` / `MEMORY STATS` / `MEMORY USAGE <key>` |
| Connections | `CLIENT LIST` / `CLIENT INFO` |
| RQE / Search | `FT.INFO <idx>` / `FT.PROFILE <idx> SEARCH QUERY "..."` |
The two most useful for incident triage:
- **`SLOWLOG GET`** to find queries that exceeded the `slowlog-log-slower-than` threshold (10ms by default). The output shows the exact command and duration in microseconds.
- **`MEMORY DOCTOR`** for memory pressure — it returns a one-paragraph summary of what's unusual about memory usage right now.
```python
for entry in redis.slowlog_get(10):
print(f"{entry['duration']}μs {entry['command']}")
```
See [references/commands.md](references/commands.md).
## 3. Redis Insight
For interactive use (running queries, browsing keys, profiling indexes), [Redis Insight](https://redis.io/insight/) is the official GUI. It surfaces the same `SLOWLOG` / `INFO` / `FT.PROFILE` data visually and includes Redis Copilot for natural-language queries. Useful during development and incident response; not a replacement for exporting metrics to your monitoring system.
## References
- [Redis: Latency monitoring](https://redis.io/docs/latest/operate/oss_and_stack/management/optimization/latency/)
- [Redis Insight](https://redis.io/insight/)
Referenced files: 3
redis-search11.1 KB
---
name: redis-search
description: Redis Search guidance covering FT.CREATE schema design, field type selection (TEXT, TAG, NUMERIC, GEO, GEOSHAPE, VECTOR, JSON path), DIALECT 2 query syntax, FT.SEARCH / FT.AGGREGATE / FT.HYBRID command selection, vector similarity with HNSW or FLAT, hybrid retrieval combining lexical and vector ranking, RAG pipelines, zero-downtime index updates via aliases, and debugging with FT.PROFILE and FT.EXPLAIN. Use when defining a search index on Hash or JSON documents, writing FT.SEARCH queries with filters, sorting, aggregation, or vector KNN, tuning HNSW parameters, building a RAG retrieval pipeline, or troubleshooting slow or empty search results.
license: MIT
---
# Redis Search
Single source of guidance for Redis Search — the retrieval surface that spans lexical, numeric, geo, JSON-path, and vector queries. Vector fields are part of the same `FT.CREATE` machinery as TEXT/TAG/NUMERIC fields, and `FT.HYBRID` blends lexical and vector ranking in one command, so this skill covers them together.
## When to apply
- Creating, modifying, or reviewing a Redis Search index (`FT.CREATE`, `FT.ALTER`).
- Writing or optimizing `FT.SEARCH`, `FT.AGGREGATE`, or `FT.HYBRID` queries.
- Picking between `TEXT`, `TAG`, `NUMERIC`, `GEO`, `GEOSHAPE`, `VECTOR`, or JSON-path fields.
- Defining a `VECTOR` field, choosing HNSW vs FLAT, tuning HNSW parameters.
- Building a retrieval-augmented generation (RAG) pipeline.
- Rolling out a new index schema without downtime.
- Troubleshooting empty results, slow queries, or tokenization issues with `FT.EXPLAIN`, `FT.PROFILE`, `FT.INFO`.
## 1. Pick the right command
Three query commands. Reach for the narrowest one that fits.
| Command | When to use | Mental model | Minimum Redis |
|---|---|---|---|
| **FT.SEARCH** | Document retrieval, ranked or sorted. Best default. | Returns matching docs directly. | 2.0 (module) / 8.0 (built-in) |
| **FT.AGGREGATE** | Faceting, computed fields, custom output shape, analytics. | Declarative pipeline: `LOAD`, `APPLY`, `GROUPBY`, `REDUCE`, `SORTBY`. | 2.0 / 8.0 |
| **FT.HYBRID** | Blend lexical (BM25) with vector similarity, with configurable fusion. | Pipeline with explicit `SEARCH` + `VSIM` legs and a `COMBINE` fusion stage. | **8.4.0** |
```
# FT.SEARCH — most common
FT.SEARCH idx:products "@category:{electronics} @price:[100 500]" LIMIT 0 20 RETURN 3 name price category
# FT.AGGREGATE — top categories by avg price
FT.AGGREGATE idx:products "*" GROUPBY 1 @category REDUCE AVG 1 @price AS avg_price SORTBY 2 @avg_price DESC
# FT.HYBRID (Redis ≥ 8.4) — lexical + vector fusion
FT.HYBRID idx:docs
SEARCH "@title:transformers" SCORER BM25 YIELD_SCORE_AS lexscore
VSIM embedding $vec KNN count 1 K 50 YIELD_SCORE_AS vecscore
COMBINE RRF 2 CONSTANT 60
PARAMS 2 vec "..."
DIALECT 2
```
For Redis < 8.4 the lexical+vector blend is approximated with `FT.SEARCH` pre-filter + `=>[KNN ...]`. See [references/command-selection.md](references/command-selection.md) and [references/hybrid-search.md](references/hybrid-search.md).
## 2. Schema basics — `FT.CREATE`
`FT.CREATE` indexes Hash or JSON documents matching a `PREFIX`. Always set `PREFIX`. Use `DIALECT 2` (the default since Redis 8; required for vector queries).
```
FT.CREATE idx:products ON HASH PREFIX 1 product:
SCHEMA
name TEXT WEIGHT 2.0
category TAG SORTABLE
price NUMERIC SORTABLE
location GEO
embedding VECTOR HNSW 6
TYPE FLOAT32
DIM 1536
DISTANCE_METRIC COSINE
```
Pick the narrowest field type that supports your access pattern:
| Field type | Use when | Notes |
|---|---|---|
| `TEXT` | Full-text search | Tokenized + stemmed; **not** for exact match |
| `TAG` | Exact match / filtering | Add `SORTABLE UNF` for fastest tag queries |
| `NUMERIC` | Range queries, sorting | Prices, counts, timestamps |
| `GEO` | Lat/long points | Stores, users |
| `GEOSHAPE` | Polygon / area queries | Delivery zones, regions |
| `VECTOR` | Similarity search | HNSW or FLAT; see §4 |
| JSON `$.path AS alias` | Nested JSON fields | `ON JSON`; see [references/json-indexing.md](references/json-indexing.md) |
The classic mistake is `TEXT` for a category or status field "because it's a string" — `TAG` is roughly 10× faster for exact-match filtering.
See [references/index-creation.md](references/index-creation.md), [references/field-types.md](references/field-types.md), [references/dialect.md](references/dialect.md), [references/ft-create-options.md](references/ft-create-options.md), [references/json-indexing.md](references/json-indexing.md).
## 3. Common queries
Narrow with filters; return only what you need.
```
# Tag filter + numeric range, sorted by price
FT.SEARCH idx:products "@category:{electronics} @price:[100 500]"
SORTBY price ASC
LIMIT 0 20
RETURN 3 name price category
# Text + tag filter
FT.SEARCH idx:products "wireless headphones @category:{audio}"
# Negation and OR
FT.SEARCH idx:products "@category:{audio} -@brand:{generic} (@price:[0 100] | @on_sale:{true})"
```
Operators worth remembering: space = AND, `|` = OR, `-` = NOT, `~` = optional (scoring boost), `=>{$weight: N}` = boost. Escape hyphens and special characters inside TAG values (`@sku:{ABC\\-123}`). See [references/query-syntax.md](references/query-syntax.md) and [references/search-syntax-primitives.md](references/search-syntax-primitives.md) for the DSL vocabulary.
For tokenization gotchas (stemming, stopwords, language) see [references/text-tokenization.md](references/text-tokenization.md). For result shaping (`SORTBY`, `RETURN`, `HIGHLIGHT`, `SUMMARIZE`, `NOCONTENT`) see [references/result-shaping.md](references/result-shaping.md). For performance levers (pre-filters, `SORTABLE` fields, tight `RETURN`, `FT.PROFILE`) see [references/query-optimization.md](references/query-optimization.md).
## 4. Vector basics
Three vector settings have to match the embedding model exactly:
- **`DIM`** — output dimensionality (e.g. 1536 for OpenAI `text-embedding-3-small`). Mismatch produces silent garbage.
- **`DISTANCE_METRIC`** — `COSINE` for normalized text embeddings (common case), `IP` for unnormalized inner-product, `L2` for raw Euclidean.
- **`TYPE`** — usually `FLOAT32`. Use `FLOAT16` or quantized variants only when memory is the binding constraint.
```
# Index
FT.CREATE idx:docs ON HASH PREFIX 1 doc:
SCHEMA
content TEXT
embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
# Pure KNN query (top 5 by cosine similarity)
FT.SEARCH idx:docs "*=>[KNN 5 @embedding $vec AS score]"
PARAMS 2 vec "..."
SORTBY score
DIALECT 2
```
| Algorithm | Speed | Accuracy | Memory | Use for |
|---|---|---|---|---|
| **HNSW** | Fast (approximate) | ~95%+ recall (tunable) | Higher | Production: >10k vectors, latency-sensitive |
| **FLAT** | Slow (exact) | 100% | Lower | Small corpora (<10k), exact-match required |
HNSW tuning levers: `M` (16–64, connections per node), `EF_CONSTRUCTION` (100–500, build quality), `EF_RUNTIME` (query-time candidate list).
See [references/vector-query.md](references/vector-query.md), [references/algorithm-choice.md](references/algorithm-choice.md).
## 5. Hybrid retrieval
Two distinct patterns get called "hybrid." Pick by intent.
**Filter-then-vector** (any Redis version) — apply attribute filters so the engine narrows the search space *before* the vector comparison.
```
FT.SEARCH idx:docs "(@category:{tech} @date:[2024 +inf])=>[KNN 10 @embedding $vec AS score]"
PARAMS 2 vec "..."
SORTBY score
DIALECT 2
```
**Lexical + vector fusion** (Redis ≥ 8.4) — blend BM25 text scoring with vector similarity, fuse with `RRF` or `LINEAR`. Use `FT.HYBRID` (see §1).
Don't fetch a wide unfiltered result and filter client-side — slower and less accurate. See [references/hybrid-search.md](references/hybrid-search.md).
## 6. Aggregations and shaping
`FT.AGGREGATE` is the declarative result-shaping command. Build a pipeline of stages.
```
# Top 5 categories by total revenue
FT.AGGREGATE idx:orders "@status:{shipped}"
LOAD 2 @category @amount
GROUPBY 1 @category
REDUCE SUM 1 @amount AS revenue
SORTBY 2 @revenue DESC
LIMIT 0 5
```
Common stages: `LOAD`, `APPLY` (computed fields), `FILTER` (post-query), `GROUPBY` + `REDUCE` (`SUM`, `COUNT`, `AVG`, `FIRST_VALUE`, `TOLIST`), `SORTBY`, `LIMIT`.
For long-running result sets use `WITHCURSOR` + `FT.CURSOR READ` to page server-side. See [references/aggregate-pipeline.md](references/aggregate-pipeline.md) and [references/aggregate-cursors.md](references/aggregate-cursors.md).
## 7. RAG pattern
Standard pipeline: embed the query, vector-search Redis, pass top-K context to the LLM.
Practical tips:
- **Match the metric** to the embedding model (almost always `COSINE` for normalized text models).
- **Chunk long documents** (200–500-token chunks usually beat indexing whole pages).
- **Batch inserts** rather than one call per record.
- **Pre-filter with attributes** (tenant, recency, document type) before the vector search — see §5.
- **Re-rank** at the top of the funnel if precision matters more than recall.
See [references/rag-pattern.md](references/rag-pattern.md).
## 8. Operations
Zero-downtime schema changes: keep app queries pointed at an alias and swap the underlying index.
```
FT.CREATE idx:products_v2 ON HASH PREFIX 1 product: SCHEMA ...
FT.ALIASUPDATE products idx:products_v2
# App queries are stable:
FT.SEARCH products "@category:{electronics}"
```
Useful management commands: `FT.INFO`, `FT.DROPINDEX`, `FT._LIST`, `FT.ALIASADD/UPDATE/DEL`. See [references/index-management.md](references/index-management.md).
Debug empty or slow queries with `FT.EXPLAIN` (shows how the query was parsed) and `FT.PROFILE` (shows execution stats). See [references/debugging.md](references/debugging.md).
## 9. Client examples
Inline examples in this SKILL.md are CLI / RESP form — the wire protocol every client serializes to. For idiomatic snippets in a specific client:
- **redis-py** (Python, raw client): [references/clients/python-redis-py.md](references/clients/python-redis-py.md)
- **Jedis** (Java): [references/clients/java-jedis.md](references/clients/java-jedis.md)
- **RedisVL** (Python, higher-level SDK on top of redis-py): [references/clients/python-redisvl.md](references/clients/python-redisvl.md)
Other clients (Lettuce, node-redis, go-redis, NRedisStack, .NET) translate the same CLI form; coverage is tracked as a follow-up.
## References
- [Redis: Search and query](https://redis.io/docs/latest/develop/interact/search-and-query/)
- [Redis: Vectors](https://redis.io/docs/latest/develop/ai/search-and-query/vectors/)
- [Redis: Query syntax](https://redis.io/docs/latest/develop/interact/search-and-query/query/)
- [Redis: Query dialects](https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/dialects/)
- [Redis: RAG quickstart](https://redis.io/docs/latest/develop/get-started/rag/)
- [FT.CREATE](https://redis.io/docs/latest/commands/ft.create/) · [FT.SEARCH](https://redis.io/docs/latest/commands/ft.search/) · [FT.AGGREGATE](https://redis.io/docs/latest/commands/ft.aggregate/) · [FT.HYBRID](https://redis.io/docs/latest/commands/ft.hybrid/)
- [RedisVL documentation](https://docs.redisvl.com/en/latest/)
Referenced files: 23
redis-security3.55 KB
---
name: redis-security
description: Redis security guidance covering authentication (requirepass and ACL users), TLS, ACL-based least-privilege access control, restricting network exposure via bind and protected-mode, firewall rules, and disabling dangerous commands. Use when deploying Redis to production, defining ACL users for an application, configuring TLS connections, locking down a Redis instance behind a firewall, or auditing a Redis deployment for security hardening.
license: MIT
---
# Redis Security
Production hardening for Redis: authentication, ACL-based access control, and network exposure. Cover all three together — any one of them on its own leaves an exploitable gap.
## When to apply
- Deploying or reviewing a Redis instance destined for production.
- Setting up application credentials beyond a shared password.
- Auditing a Redis deployment against a security checklist.
- Receiving "Redis exposed to the internet" findings from a scanner.
## 1. Always authenticate (and use TLS)
Never run a production Redis without a password. Pair authentication with TLS so credentials and data aren't sent in clear text.
```
# redis.conf
requirepass your-strong-password
tls-port 6380
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key
```
```python
r = redis.Redis(
host="localhost",
port=6380,
password="your-strong-password",
ssl=True,
ssl_cert_reqs="required",
)
```
If you can use ACL users (next section) instead of the single `requirepass`, do — `requirepass` is effectively the legacy "default user" shortcut.
See [references/auth.md](references/auth.md).
## 2. ACLs for least-privilege access
The `default` user with a shared password is fine for development. For production, give each application a dedicated ACL user with only the commands and key patterns it actually needs.
```
# Cache-only reader
ACL SETUSER app_readonly on >password ~cache:* +get +mget +scan
# Writer that can't run dangerous ops
ACL SETUSER app_writer on >password ~* +@all -@dangerous
# Admin (use sparingly, never for application traffic)
ACL SETUSER admin on >strong-password ~* +@all
```
Useful command categories:
| Category | What it covers |
|---|---|
| `@read` | Read commands (`GET`, `MGET`, `HGET`, ...) |
| `@write` | Write commands (`SET`, `DEL`, `XADD`, ...) |
| `@dangerous` | `FLUSHALL`, `DEBUG`, `KEYS`, etc. |
| `@admin` | Administrative commands |
If app credentials leak, a tight ACL bounds the blast radius — the attacker can't `FLUSHALL` your DB just because they grabbed a cache reader's password.
See [references/acls.md](references/acls.md).
## 3. Restrict network access
The most common Redis breach is a public-internet Redis with no auth. Avoid that with three layers:
```
# redis.conf — bind to specific interfaces, keep protected-mode on
bind 127.0.0.1 192.168.1.100
protected-mode yes
```
```bash
# Firewall — allow only application subnets
iptables -A INPUT -p tcp --dport 6379 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 6379 -j DROP
```
Anti-pattern: `bind 0.0.0.0` + `protected-mode no` — exposes Redis to the whole network without protection.
Optional but recommended: rename or disable destructive commands so a compromised client can't trash the DB:
```
rename-command FLUSHALL ""
rename-command DEBUG ""
rename-command CONFIG ""
```
See [references/network.md](references/network.md).
## References
- [Redis: Security](https://redis.io/docs/latest/operate/oss_and_stack/management/security/)
- [Redis: ACL](https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/)
Referenced files: 4
redis-semantic-cache3.96 KB
---
name: redis-semantic-cache
description: Redis LangCache guidance for semantic caching of LLM responses on Redis Cloud — calling search/set via the SDK or REST API, tuning the similarity threshold, separating caches per task type, and filtering with custom attributes. Use when caching LLM completions or RAG answers to cut API cost and latency, building a cache-aside layer in front of OpenAI / Anthropic / etc., tuning hit rate vs precision, or splitting one app's LLM workloads into multiple LangCache caches.
license: MIT
---
# Redis Semantic Cache
Semantic caching for LLM responses with Redis Cloud's LangCache service. Stores prompts as embeddings; subsequent semantically-similar prompts return the cached response without re-calling the model.
> LangCache is currently in **preview** on Redis Cloud. Features and behavior may change.
## When to apply
- Wrapping an LLM call (OpenAI, Anthropic, etc.) with a cache layer to cut cost and latency.
- Caching RAG answers, classification outputs, or any deterministic LLM workload.
- Tuning the precision/hit-rate trade-off for a semantic cache.
- Splitting one application's LLM workloads across multiple cache instances.
## 1. The cache-aside flow
LangCache fits in front of any LLM call as a standard cache-aside pattern:
1. Send the user's prompt to LangCache's `search`.
2. **Cache hit** — return the stored response directly.
3. **Cache miss** — call the LLM, then `set` the response so future similar prompts hit.
```python
from langcache import LangCache
import os
lang_cache = LangCache(
server_url=f"https://{os.getenv('HOST')}",
cache_id=os.getenv("CACHE_ID"),
api_key=os.getenv("API_KEY"),
)
result = lang_cache.search(prompt="What is Redis?", similarity_threshold=0.9)
if result:
response = result[0]["response"]
else:
response = llm.generate("What is Redis?")
lang_cache.set(prompt="What is Redis?", response=response)
```
The same operations are available via REST (`POST /v1/caches/{cacheId}/entries/search` and `POST /v1/caches/{cacheId}/entries`) when an SDK isn't an option.
See [references/langcache-usage.md](references/langcache-usage.md) for full SDK + REST samples and attribute-based storage.
## 2. Tune the similarity threshold
The threshold controls how close (in embedding cosine distance) a new prompt must be to a cached one to count as a hit. Higher = stricter match, fewer false positives. Lower = more hits, more risk of returning an off-topic answer.
| Threshold | Behavior | Use when |
|---|---|---|
| 0.95+ | Near-exact match required | Customer-facing answers where wrong responses are costly |
| 0.9 | Balanced default | Most workloads — start here |
| 0.8 | Loose semantic match | Internal tools, exploratory queries, FAQ deduplication |
```python
# Stricter — fewer false positives
result = lang_cache.search(prompt="What is Redis?", similarity_threshold=0.95)
# Looser — higher hit rate
result = lang_cache.search(prompt="What is Redis?", similarity_threshold=0.8)
```
Adjust by watching the actual cache-hit rate and spot-checking that returned answers are still relevant.
See [references/best-practices.md](references/best-practices.md).
## 3. Separate caches per task type
Different LLM workloads should not share one cache — a "code question" prompt is semantically close to other code questions but has nothing to do with a password-reset support query, and crossing them returns garbage.
```python
support_cache = LangCache(server_url=..., cache_id="support-cache-id", api_key=...)
code_cache = LangCache(server_url=..., cache_id="code-cache-id", api_key=...)
```
Create distinct cache IDs in Redis Cloud per task, and route each call to the right one. As a finer-grained alternative, store and search with **custom attributes** (e.g. `{"category": "database"}`) to keep tasks in the same cache but isolated by attribute filter — useful when the same prompt format spans subtopics.
## References
- [LangCache documentation](https://redis.io/docs/latest/develop/ai/langcache/)
Referenced files: 3
Package details
Publisher declarations from the archived package. These are separate from our research and the live service's terms.
- Package license
- MIT
- Package author
- Redis
- Keywords
- redis, database, caching, vector-search, performance, best-practices
Declared capabilities
- Read
- Write
Package observed Oct 2, 2026.
Technical details
- First seen
- Sep 30, 2026 · 22:02 UTC
- Last seen
- Oct 2, 2026 · 18:00 UTC
- Collection status
- Collected
plugins_6a85b91f8aa081918a9daf1444559586
Download plugin data (JSON)