/upstash:redis-best-practicesfrom Upstash Redis
Production Redis performance rules covering batching, eviction, pipelines, Lua scripts, connection pooling, and error handling. Use when debugging slow Redis, high memory, or choosing between MGET, SCAN, and WATCH.
Ships in Upstash Redis. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Rules for code that talks to Redis, on any deployment. They come from real support cases and from tests on two engines:
Engines differ. Stock Redis runs commands on one main thread, so one slow command stalls every client. Valkey, managed services and Upstash change some defaults and limits. Rules below apply everywhere unless they name an engine, and On Upstash collects what differs there.
Half the trouble in support comes from databases that are neither, growing until writes fail or keys vanish. A cache with no expirations and a high miss rate only grows.
Know the eviction policy. Open source Redis defaults to noeviction, which fails writes at the limit, and some managed services default to volatile-lru. For a pure cache, use allkeys-lru or allkeys-lfu, but remember they delete keys you may not be able to reload. volatile-* policies only evict keys with a TTL, so a store without TTLs frees nothing. Eviction is sampled and approximate, so keep headroom. A database pinned at its limit evicts all day.
| Need | Use |
|---|---|
| Read many plain keys | MGET in chunks of 1,000 |
| Write many plain keys | MSET in chunks of 1,000 |
| Read many fields of one hash | HMGET |
| Mixed commands | Pipeline in chunks of 1,000 |
| All or nothing | MULTI/EXEC |
A pipeline saves round trips, never commands. MGET is one command, so it beats a pipeline of GETs wherever it fits. Reading 1,000 keys:
| Distance to the database | Await each GET | Pipeline | MGET |
|---|---|---|---|
| Same machine (stock Redis) | 46 ms | 3.6 ms | 1.3 ms |
| 1 ms (Upstash) | 1,023 ms | 6.7 ms | 3.8 ms |
| 116 ms (Upstash) | 118,016 ms | 172 ms | 140 ms |
Always chunk. Redis queues replies in memory, and normal clients have no output buffer limit by default. While stock Redis read 200,000 keys of 1 KB, another client's slowest read was 48.8 ms during one pipeline and 73.9 ms during one MGET, against 0.84 ms and 0.51 ms in chunks of 1,000. Lower the chunk size when values are large, because reply bytes are the real cost.
A pipeline isn't atomic, so if it fails partway, the commands before the failure stay applied. On a cluster, MGET and MSET need all their keys in one slot, so use hash tags or a pipeline per node.
Details and numbers: Why MGET Is Faster Than a Redis Pipeline for Reading Many Keys
HGETALL took 1,126 ms and stalled another client for 96 ms, while HMGET of 10 fields took 0.4 ms.UNLINK. On stock Redis at 1 million fields, DEL took 319 ms and stalled another client for 314 ms, while UNLINK took 0.3 ms. Lazy freeing is off by default in Redis, and on by default in Valkey 8.XADD ... MAXLEN ~ 1000 or MINID, LTRIM after every LPUSH, and a TTL on temporary results, including anything a *STORE command produces.redis-cli --bigkeys, --memkeys, --hotkeys (needs an LFU policy) and MEMORY USAGE.Details and numbers: How Big Should a Redis Key Be?
SET key value EX ttl in one command.Details and numbers: How TTL Jitter Protects Your Database When Redis Keys Expire Together
| Instead of | Use | Why |
|---|---|---|
KEYS in code | SCAN, or an index set | KEYS walks the whole keyspace in one call. With 1 million keys on stock Redis, ten calls at once stalled another client for 823 ms, against a normal read of 0.08 ms |
SCAN with a low COUNT | COUNT 1000 | MATCH filters after the walk, so finding 100 keys among 1 million took 9,953 pages at COUNT 100 and 1,000 at COUNT 1000 |
| Sweeping for the same keys repeatedly | A set that holds their names | One database swept its keyspace 525 times a day, and another once a second from edge functions |
HGETALL, SMEMBERS, LRANGE 0 -1 | HMGET, SSCAN, LRANGE windows | Whole-collection reads grow with the data |
XRANGE key - + | XRANGE with COUNT, paging from the last ID | Same reason, and some engines limit the reply |
SET then EXPIRE | SET key value EX ttl | One command, and no key left without a TTL |
EXISTS then SET | SET key value NX | One command, no race |
EXISTS then GET | GET | One command |
SORT | A sorted set, or sort on the client | O(N log N) on the server |
INFO, DBSIZE, CONFIG GET as health checks | PING | Some clients run these on every connection |
*STORE on every call | Update the result on write, or ZRANGESTORE ... LIMIT | Each call recomputes the whole result. One database ran 740 K ZINTERSTORE a day |
FLUSHDB in code | SCAN plus UNLINK by prefix, and separate databases per environment | One copied console command wipes the data |
Polling XLEN, XPENDING or TTL in a loop | XREADGROUP ... COUNT n BLOCK 5000 | One consumer group ran 1.3 M reads a day against 850 K acknowledgements |
MONITOR in production. It streams every command to one client, and can cut throughput by more than half.XACK, use XAUTOCLAIM for dead consumers, and add a dead-letter path. Trimming a stream doesn't clear its pending entries by default.service:entity:id, and keep names short. Prefer prefixes to numbered databases, which clusters and many managed services don't offer. Use hash tags like {tenant} when multi-key commands or scripts must see keys together.SCRIPT alone.Details and numbers: How to List Keys in Redis Safely With SCAN
Use the built-in command first (INCR, SET NX), then a short Lua script, and WATCH only when few clients share a key. These are 1,000 updates to one key with 25 clients:
| Method | Stock Redis | Upstash |
|---|---|---|
| Plain read then write | 959 updates lost, no error | 940 updates lost, no error |
WATCH with retries | 1.6 s, 101 commands per update, 132 gave up | 8.1 s, 91 commands per update, 10 gave up |
| Lua script | 27 ms | 97 ms |
WATCH gets worse with distance, because an attempt takes three round trips. From 116 ms away, 200 updates with 25 clients took 55 s, against 1 s for Lua.
#!lua flags=allow-key-locking so they lock only their own keys. Open source Redis and Valkey have no such flag and reject the script, so leave it off there.busy-reply-threshold (5 s by default) doesn't stop a script. Past it, other clients get BUSY errors, 1,124 of them during one 8 second script. After a script writes, the only way to stop it is SHUTDOWN NOSAVE.KEYS or SCAN or read a whole collection in a script. Don't build big tables or strings in Lua. Page with arguments from the client, and serialize on the client.KEYS and every value through ARGV. Clusters need declared keys to route the call. A body with a value baked in is a new script every call, and since Redis 7.4, EVAL scripts past 500 get evicted.SCRIPT LOAD, and call EVALSHA with an EVAL fallback for NOSCRIPT.MULTI. A script is already atomic.SET key token NX PX ttl, and release with a script that checks the token. Always set a TTL on the lock. On Redis 8.4 and later, DELEX key IFEQ token releases without a script.Details and numbers: Why Lua Scripts Beat WATCH When Many Clients Update One Redis Key
GET on a reused TLS connection and 7.8 ms with a new one each time. AWS measured 0.21 ms against 2.82 ms. We saw databases at 112 K connections a day with 9 commands each.ECONNRESET. Proxies and load balancers close idle sockets.maxclients (10,000 by default): pool size times processes times regions, before the next scale-out.INCR, LPUSH and most scripts aren't safe to replay.CLIENT SETINFO per service, so the server can say which fleet did it.-@dangerous. Don't run production on the default user. Use ACLs in place of the deprecated rename-command.AUTH a day from a deployment nobody remembered.rediss:// with TLS on.Watch five numbers. Every incident behind these rules was visible in one of them a week ahead:
| Number | Where to read it on stock Redis |
|---|---|
| Miss rate | keyspace_hits, keyspace_misses in INFO |
| Slow commands and command mix | SLOWLOG (over 10 ms by default, excludes network time), INFO commandstats, LATENCY DOCTOR (monitor is off by default) |
| Memory against the limit | used_memory, maxmemory, evicted_keys |
| Connections against the limit | connected_clients, rejected_connections |
| Replication and write latency | sync_full, replica offsets, the client's write latency tail |
| Error | Meaning | Fix |
|---|---|---|
OOM command not allowed when used memory > 'maxmemory' | The database is at its memory limit, with noeviction or nothing it can evict | Add TTLs, choose an eviction policy, or raise the limit |
BUSY Redis is busy running a script | A script ran past busy-reply-threshold | SCRIPT KILL if it hasn't written, then shorten the script |
NOSCRIPT No matching script | The script isn't in the server's cache | Fall back to EVAL |
CROSSSLOT Keys in request don't hash to the same slot | A multi-key command spans cluster slots | Use hash tags, or split the call |
ERR Unexpected flag in script shebang: allow-key-locking | The flag only exists on Upstash, and this is open source Redis or Valkey | Remove the flag on this server |
EXECABORT | A queued command was invalid, so the transaction was discarded | Fix the command and retry |
Upstash runs its own engine: disk-backed, with per-key locks. A slow command usually stalls only its own key, and limits turn many stalls into errors. If Upstash MCP tools are available, read the database's stats and command mix through them first.
MGET 1, and a script 1 plus 1 per redis.call. An aborted EXEC still bills.MGET in chunks.HGETALL failed past about 200,000 small fields, and LRANGE 0 -1 at 14 MB.optimistic-volatile, which samples at random and prefers keys with a TTL.KEYS: fails above about 5,000 results, and for any pattern once the database holds about 100,000 keys, so code that passed in testing can break in production.SCAN: a fixed prefix found 100 keys among 1 million in 1 page and 2 ms, while a leading wildcard took 93 pages and 607 ms. COUNT above 1,000 had no effect.XRANGE key - +: returns at most 1,000 entries with no error.HLEN on a 1 million field hash took 566 ms once on Pay as You Go, and 9.4 s repeatedly on a free database with 64 MB of memory. Clients of that key wait, while unrelated keys stay at about 1 ms. One HSCAN page cost 276 ms at that size, so split instead of paging. DEL and UNLINK both returned in 0.9 ms.#!lua flags=allow-key-locking and passing every key through KEYS. It then locks only those keys, and the same client lost 13%. @upstash/ratelimit runs its scripts this way since 2.1. It made no difference on a free database. Inside MULTI, a script always takes the global lock.createScript in @upstash/redis handles the EVALSHA fallback.WATCH: needs TCP, since the REST API doesn't support it.@upstash/redis uses HTTP, so it needs no pool. Use 1.38.4 or later for readYourWrites.SLOWLOG, so use the console and Prometheus metrics. INFO counters are per replica. Prometheus, Datadog and the console's Insights need Prod Pack or an Enterprise plan.| Error | Meaning | Fix |
|---|---|---|
ERR max request size exceeded | One command or reply is over the plan's limit | Chunk it, or read in pages |
ERR max requests limit exceeded | The monthly command quota ran out, and the server closes the connection partway through a pipeline | Send fewer commands, or upgrade |
ERR too many keys to fetch, please use SCAN | KEYS matched more than about 5,000 keys | SCAN |
ERR KEYS command is disabled because total number of keys is too large | The database holds about 100,000 keys or more | SCAN or an index set |
ERR Error running script: execution timed out | The script ran past the time limit, and its earlier writes stay | Shorten it, and run many short calls |
ERR Dynamic keys are not allowed in Lua scripts | A script with allow-key-locking touched a key it didn't declare | Pass the key through KEYS |
ERR XReadGroup is cancelled | The consumer's pending list is near the limit of 1,000 | XACK, and read fewer at a time |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
14 skills in this plugin
/upstashWork with any Upstash product, SDK, or tool, including serverless Redis (caching, sessions, leaderboards, key-value storage), Ratelimit (rate limiting and throttling), QStash (message queue, cron schedules, background jobs), Workflow (durable long-running functions), Vector (vector database for embeddings, semantic search, and RAG), Search (full-text and semantic search), Box (sandboxed cloud containers for AI agents, TypeScript/JavaScript and Python), Blob (file storage and user uploads for images, videos and attachments, S3-compatible, with direct browser uploads and a global CDN by default), and the Upstash CLI. Use when the user mentions Upstash or needs any of these capabilities in a serverless, edge, or Node.js app./upstash-blob-jsWork with the @upstash/blob TypeScript/JavaScript SDK for S3-compatible object storage with direct browser uploads, presigned URLs, multipart, and signed reads. Use when storing files or blobs, uploading avatars, images, videos, attachments or user documents, letting a browser upload straight to storage without proxying bytes through a server, generating public or time-limited signed URLs, serving private files, streaming large files with pause and resume, setting cache headers on stored objects, or reaching an S3-compatible bucket from the AWS SDK./upstash-box-cliDrive an Upstash Box (a remote sandboxed workspace) from the terminal with the `box` CLI. Use when asked to run commands, edit files, clone repos, run builds or tests, publish a public URL, browse or screenshot a page, open a pull request or issue with a screenshot attached, schedule recurring work, run an AI agent, or do any work inside a box rather than on this machine./upstash-box-jsWork with the @upstash/box TypeScript/JavaScript SDK for sandboxed cloud containers with AI agents, shell, filesystem, git, cron schedules, snapshots, and a headless browser. Use when building with Upstash Box, creating a sandbox or isolated environment to run untrusted or agent-generated code, running AI coding agents in containers, giving an agent a cloud dev environment with a shell and repository, browser automation from a box, scheduling recurring jobs inside a box, saving and restoring snapshots, or orchestrating parallel boxes./upstash-box-pyWork with the upstash-box Python SDK for sandboxed cloud containers with AI agents, shell, filesystem, git, cron schedules, snapshots, and a headless browser. Use when building with Upstash Box in Python, creating a sandbox or isolated environment to run untrusted or agent-generated code, running AI coding agents in containers, giving an agent a cloud dev environment with a shell and repository, browser automation from a box, scheduling recurring jobs inside a box, saving and restoring snapshots, or orchestrating parallel boxes./upstash-box-remote-workDo work in an Upstash Box, a sandboxed cloud container driven through the remote Upstash MCP server (mcp.upstash.com), instead of on the local machine. Use when the user asks to run, build, test, clone, or edit something remotely, in a sandbox, in the cloud, or in a box, when the deliverable is a pull request, a public preview URL, or a screenshot of a running app, when the local machine cannot deliver (no GitHub login for gh, no way to expose a port, a dirty or slow local checkout), when several independent tasks should run in parallel on separate machines, or a code factory that turns a list of tasks into a list of pull requests. Applies whenever the session has the box_* and blob_* MCP tools, even when Upstash is not named.npx claudepluginhub upstash/skills --plugin upstashOther plugins' skills for the same job