redis 100 Q&As

Redis FAQ & Answers

100 expert Redis answers researched from official documentation. Every answer cites authoritative sources you can verify.

unknown

100 questions
A

Redis (REmote DIctionary Server) is an in-memory data structure store used as database, cache, message broker, and streaming engine. Single-threaded with I/O multiplexing for millisecond-level latency. Redis 8 (GA 2025) supports 15+ data structures: strings, hashes, lists, sets, sorted sets, streams, JSON, vector sets (beta), time series, geospatial indexes, bitmaps, HyperLogLog, and probabilistic structures (Bloom filters, cuckoo filters, t-digest, top-k, count-min sketch). Persistence via RDB snapshots or AOF (append-only file). Stores all data in RAM with optional disk persistence. Horizontal scaling via Redis Cluster (16384 hash slots). High availability through replication and Redis Sentinel.

99% confidence
A

Redis primary use cases: caching (sub-millisecond latency), session storage, real-time analytics, rate limiting, leaderboards, pub/sub messaging, job queues, geospatial queries, time-series data, user tracking, message queuing, event streaming. Excellent for high-performance scenarios requiring low latency data access. Common in web applications for session management, in e-commerce for shopping carts, in gaming for leaderboards, and in analytics for real-time dashboards.

Sources
99% confidence
A

Redis Strings: simple key-value binary data, maximum 512MB per string. Binary-safe (can store images, serialized objects). Commands: SET/GET, INCR/DECR, APPEND, MGET, STRLEN. Atomic operations on single keys. Can store integers (up to 2^63) with atomic increment/decrement. Memory efficient for small values. Used as building blocks for other data types. Most basic Redis data type, supports bit operations (GETBIT, SETBIT, BITCOUNT).

99% confidence
A

Use Redis Strings for: caching values, counters (page views, API limits), session storage, rate limiting, configuration values, simple flags, binary data storage. Perfect for atomic counters (INCR, DECR operations). Store JSON blobs, user sessions, cached database results. Use when you need simple key-value storage with optional atomic increment operations. Not ideal for complex nested data - use Hashes instead.

99% confidence
A

Redis Lists: ordered collections of strings, implemented as linked lists. Commands: LPUSH/RPUSH (add to ends), LPOP/RPOP (remove from ends), LRANGE (get range), LTRIM (trim), LLEN (length). O(1) operations at ends, O(N) for middle access. Can block with BLPOP/BRPOP for queue semantics. Max length 2^32-1 elements. Each element up to 512MB. Maintains insertion order. Can be used as both queue and stack.

99% confidence
A

Use Redis Lists for: queues (job processing), stacks, activity feeds, recent items lists with LTRIM, message queues, timeline feeds. Perfect for producer-consumer patterns with BLPOP/BRPOP. Use when you need to process items in FIFO or LIFO order. Not ideal for random access by index - use Sets or Sorted Sets instead. Excellent for background job queues where workers process tasks in order.

99% confidence
A

Redis Sets: unordered collections of unique strings, O(1) operations for all basic operations. Commands: SADD (add), SREM (remove), SMEMBERS (all members), SISMEMBER (check membership), SCARD (size), SUNION (union), SINTER (intersection). Guarantees uniqueness - duplicate additions ignored. Can store up to 2^32-1 elements. Membership testing is extremely fast. Not ordered - if order matters, use Sorted Sets.

99% confidence
A

Use Redis Sets for: unique visitors tracking, tag systems, preventing duplicates, relationships (followers/following), shared interests, access control lists, inventory management. Perfect when uniqueness matters and you need fast membership testing. Use SINTER for common elements (users who liked both X and Y). Use SUNION for combining sets. Not suitable when order matters or you need associated scores.

99% confidence
A

Redis Hashes: field-value pairs within a single key, storing small objects. Commands: HSET/HGET (set/get field), HMGET/HMSET (multiple fields), HGETALL (all fields), HDEL (delete field), HEXISTS (field exists). Each hash can store up to 2^32-1 fields, each field up to 512MB. Memory efficient for small objects. Fields within hash don't have TTL individually. Think of as Redis version of a row or document.

99% confidence
A

Use Redis Hashes for: user profiles, configuration objects, caching database rows, product attributes, session data with multiple fields. Perfect when you need multiple related fields for one entity. More memory efficient than multiple top-level keys. Use HGETALL to retrieve entire object. Not ideal for very large objects (>10KB) or when you need individual field TTL. Use when you frequently access the entire object together.

99% confidence
A

Sets store unique values without additional data; Hashes store field-value pairs. Sets: SADD value, SISMEMBER value. Hashes: HSET field value, HGET field. Sets guarantee uniqueness and support set operations (union, intersection). Hashes store structured data like objects. Use Sets for uniqueness checks and collections; use Hashes for structured objects. Sets have no ordering; Hashes have field names (but no guaranteed ordering). Both provide O(1) operations.

99% confidence
A

Redis Sorted Sets: ordered collections of unique strings with associated scores (double-precision floating point). Maintained in score order with O(log N) operations. If scores equal, sorted lexicographically. Commands: ZADD (add with score), ZRANGE (by rank), ZRANGEBYSCORE (by score range), ZRANK (get rank), ZSCORE (get score), ZINCRBY (increment score). Max 2^32-1 members per sorted set. Most powerful Redis data structure for queries.

99% confidence
A

Redis Sorted Sets use cases: leaderboards (gaming scores with ZINCRBY user 1), priority queues (task scheduling with scores as priority), time-series data (timestamps as scores), rate limiting windows (activity timestamps), range queries (price ranges with ZRANGEBYSCORE), sliding windows (expire old entries), weighted rankings, auto-complete suggestions, capacity planning, resource scheduling. Perfect for anything requiring ranking or time-based ordering.

99% confidence
A

Cache-Aside (Lazy Loading): application checks cache first; on miss, fetches from database, then writes to cache. Application controls both cache and database directly. Implementation flow: 1) Try cache GET, 2) If miss, query database, 3) Write result to cache with TTL, 4) Return data. Best for read-heavy workloads where data changes occasionally. Most common Redis caching pattern due to simplicity and control.

99% confidence
A

Use Cache-Aside for: read-heavy applications, user-generated content, product catalogs, user profiles, session data. Advantages: only requested data gets cached, resilient to cache failures. Disadvantages: cache miss penalty (3 round trips), potential stale data, requires cache warming. Avoid for write-heavy workloads or real-time data requirements. Best when you can tolerate slight staleness and want to minimize cache size by storing only frequently accessed data.

99% confidence
A

RDB (Redis Database) creates point-in-time snapshots of the entire dataset at configured intervals. Generates compact single files with .rdb extension. Configuration: save 900 1 (if 1+ keys changed in 900s), save 300 10, save 60 10000. Snapshots are binary representations of memory state. Redis forks process to create snapshot without blocking operations. Files portable across Redis versions. Can be used for backups and migration.

Sources
99% confidence
A

Use RDB for: development environments, backup strategies, scenarios where occasional data loss is acceptable, fast recovery needs, disaster recovery. Excellent when backup portability and fast restarts are priorities. Redis 7+ uses hybrid RDB-AOF format combining benefits. Avoid for mission-critical data requiring maximum durability. Choose when restart speed matters more than minimal data loss, and when you can tolerate losing recent changes (between snapshots).

Sources
99% confidence
A

AOF (Append Only File) logs every write operation to provide maximum durability. Configurable fsync policies: always (every write, slowest), everysec (default, good balance), no (fastest, highest data loss risk). Files larger than RDB but provide append-only guarantee (no corruption). Redis 7+ uses optimized RDB-AOF format. Can be rewritten to minimize file size. Contains sequential log of all write commands needed to rebuild dataset state.

Sources
99% confidence
A

AOF ensures durability by appending every write command to file before acknowledging operation. With appendfsync everysec (default), Redis fsyncs every second - balances performance and durability. On restart, Redis replays all logged operations to rebuild exact state. No data corruption due to append-only nature. Can survive crashes with minimal data loss (max 1 second with everysec policy). Redis 7+ reduces restart time with hybrid RDB-AOF format.

Sources
99% confidence
A

Redis expiration policies: passive (checked on key access) and active (random sampling, evicts expired). Passive: when key accessed, check if expired. Active: every 100ms, randomly test 20 keys, delete expired ones, and if expired keys > 25%, repeat. This hybrid approach balances memory usage and CPU overhead. Works even if keys never accessed after expiration. TTL persists across save/reload (RDB saves expiration times, AOF logs DEL commands).

Sources
99% confidence
A

TTL (Time To Live) sets key expiration in seconds or milliseconds. Commands: EXPIRE key seconds, PEXPIRE key milliseconds, TTL key (remaining seconds), PTTL key (milliseconds). Set with creation: SET key value EX 3600 or SETEX. Remove with PERSIST. Once expired, key is automatically deleted. TTL precision is milliseconds but stored as integer milliseconds. Returns -1 if no expiration, -2 if key doesn't exist. Atomic operations with TTL maintain consistency.

Sources
99% confidence
A

Redis eviction policies when maxmemory reached: noeviction (return errors, default), allkeys-lru (evict least recently used), allkeys-lfu (least frequently used), allkeys-random (random eviction), volatile-lru (only keys with TTL), volatile-lfu (TTL + LFU), volatile-random (TTL + random), volatile-ttl (shortest TTL first). Policies with 'volatile' only consider keys with expiration set. Set with CONFIG SET maxmemory-policy policy_name. Different memory management strategies for different use cases.

Sources
99% confidence
A

Use allkeys-lru for general caching scenarios - approximates real access patterns. Use volatile-lru when mixing cache and persistent data - only evicts temporary cache entries. Use allkeys-lfu for hot data patterns - keeps frequently accessed items regardless of recent access. Use volatile-ttl for session data - evicts closest to expiration. Use noeviction for database-like scenarios where data loss unacceptable. Choose based on data characteristics and access patterns.

Sources
99% confidence
A

Redis transactions queue commands with MULTI, execute atomically with EXEC. Commands are queued but not executed until EXEC. EXEC processes all queued commands sequentially without interruption from other clients. DISCARD cancels transaction. All commands processed or none (server crash). Transaction doesn't roll back on individual command failures - successful commands still execute. No isolation like SQL - other clients can read data during transaction (but not modify queued keys).

Sources
99% confidence
A

Redis transaction guarantees: all commands processed sequentially without interruption, all-or-nothing execution (if server crashes during EXEC, no commands applied). No automatic rollback on errors - individual command failures don't stop execution. WATCH provides optimistic locking (check-and-set) - if watched keys modified before EXEC, transaction fails. Basic atomicity and ordering guaranteed, but not full ACID properties. Use Lua scripts for more complex atomic operations with better error handling.

Sources
99% confidence
A

Redis Pub/Sub provides publish/subscribe messaging with channels. Publishers send messages with PUBLISH channel message. Subscribers receive messages with SUBSCRIBE channel. Pattern subscription with PSUBSCRIBE for multiple channels. Fire-and-forget pattern - messages not persisted, lost if no subscribers active. Low latency messaging with minimal overhead. Up to 2^32-1 channels. Messages delivered to all active subscribers (broadcast). No message persistence or delivery guarantees.

Sources
99% confidence
A

Pub/Sub workflow: Clients SUBSCRIBE to channels, become blocking receivers. Publishers PUBLISH messages to channels, all active subscribers immediately receive. Redis maintains active subscriptions in memory. Messages delivered in order received. No queuing for offline subscribers. PSUBSCRIBE matches patterns (user:, news:tech). UNSUBSCRIBE removes subscriptions. Client can subscribe to multiple channels simultaneously. Subscriptions survive connection drops if client reconnects.

Sources
99% confidence
A

Redis Streams provide persistent, append-only logs with consumer groups. Each entry has unique ID (timestamp-sequence). Commands: XADD stream * field value (append entry), XREAD COUNT streams stream $ (read from end), XRANGE (range queries). Entries stored indefinitely unless trimmed (XTRIM). Supports length-based and time-based trimming. Each entry can have multiple fields. Auto-generated IDs ensure chronological ordering. Can store up to 2^64-1 entries per stream.

Sources
99% confidence
A

Redis Streams reliability: consumer groups with XGROUP CREATE stream group $ (starting from new entries) or 0 (from beginning). XREADGROUP GROUP stream consumer COUNT streams (read messages). XACK acknowledges processing. PEL (Pending Entries List) tracks unacknowledged messages. Consumers claim stale entries with XCLAIM. At-least-once delivery guaranteed. No message loss if consumer crashes - messages remain in PEL. Can reprocess failed messages. Consumer groups allow load distribution across multiple consumers.

Sources
99% confidence
A

Redis Cluster partitions data across 16384 hash slots. Each slot assigned to a master node. CRC16(key) mod 16384 determines slot. Hash tags {} force keys to same slot: {user:123}:profile and {user:123}:orders. Client library routes commands to correct node. Automatic rebalancing when adding/removing nodes. Minimum 3 masters for high availability (with optional replicas). No cross-slot operations (except Lua scripts with keys in same slot). Eventually consistent model.

Sources
99% confidence
A

Redis Cluster characteristics: horizontal scaling beyond single server RAM limits, automatic failover with replica promotion, high availability with master-replica topology, client-side routing (no proxy bottleneck), eventual consistency, minimum 3 master nodes recommended. Trade-offs: no multi-key operations across hash slots, requires cluster-aware client libraries, complex deployment and monitoring. Best for large datasets (>50GB) and high availability requirements where single-node limitations become bottleneck.

Sources
99% confidence
A

Pipelining sends multiple commands without waiting for responses, reducing round-trip time (RTT). Client buffers commands, sends batch to server, server processes sequentially, returns all responses. Commands executed in order sent. Not atomic - other clients' commands may interleave. Most Redis clients support pipelining with flush/execute methods. Different from MULTI/EXEC: no atomicity guarantees, just performance optimization. Reduces network latency impact significantly.

Sources
99% confidence
A

Pipelining improves performance by reducing network round-trips. Without pipelining: command send -> wait -> receive -> repeat (N RTTs). With pipelining: send N commands -> receive N responses (1 RTT). Performance gain proportional to network latency - 10x+ throughput on high-latency networks. Memory overhead: client buffers responses for all pipelined commands. Best for bulk operations like data import/export, batch processing, MGET/MSET with multiple keys. Combine with transactions for atomic batching when needed.

Sources
99% confidence
A

EVAL command executes Lua scripts on Redis server. Scripts access Redis via redis.call() (errors propagate) or redis.pcall() (returns errors). EVALSHA executes cached scripts by SHA1 hash. Scripts must be deterministic (no random numbers, time, external calls). Can accept parameters, return values. Scripts execute atomically - no other commands interleaved. Server can cache compiled scripts. Script execution time limited (configurable SCRIPT_TIMEOUT).

Sources
99% confidence
A

Lua script advantages: atomic execution (no interleaving with other commands), reduces round trips (complex logic on server), access to all Redis commands, better performance than client-side logic, conditional operations (if-then), read-modify-write patterns, complex data transformations. More powerful than MULTI/EXEC for complex workflows. Scripts can be reused and cached by SHA1. Essential for implementing custom data structures, complex business logic, and ensuring consistency across multiple operations.

Sources
99% confidence
A

Fixed Window Rate Limiting: INCR counter_key for each request. If counter = 1, set EXPIRE counter_key window_size_seconds. If counter > limit, reject. Simple implementation with minimal overhead. Example: redis.call('INCR', key); if tonumber(redis.call('GET', key)) == 1 then redis.call('EXPIRE', key, 60) end. Drawback: burst at window boundaries (double requests at reset). Use for simple API limiting where boundary bursts acceptable. Combine with Lua script for atomicity.

Sources
99% confidence
A

Sliding Window Rate Limiting: Use sorted set with timestamps as scores. ZADD key timestamp member, ZREMRANGEBYSCORE key 0 (now - window) to remove old entries, ZCARD key to get count in window. Example: redis.call('ZADD', key, now, uuid); redis.call('ZREMRANGEBYSCORE', key, 0, now - window); if redis.call('ZCARD', key) > limit then reject. More accurate than fixed window, eliminates boundary bursts. Higher memory usage but provides smooth rate limiting. Use with Lua script for atomicity.

Sources
99% confidence
A

RedisJSON 2.6+ (part of Redis Stack 7.2+) provides native JSON data type with JSONPath query syntax. Stores JSON documents natively, not as strings. Commands: JSON.SET key $.path value (JSONPath), JSON.GET key $.path, JSON.MERGE (RFC 7396), JSON.MSET (atomic multi-set). Supports full-text search with RediSearch integration. Performance: 5.4x faster than MongoDB for writes, 12.7x for reads (official benchmarks). Manipulates specific JSON fields without full document rewrite. Atomic operations on JSON paths prevent race conditions.

99% confidence
A

Use RedisJSON for: storing complex objects, configuration management, user profiles, product catalogs, API responses, nested data structures. Better than storing JSON as strings when you need partial updates (JSON.SET on specific path) or path-based queries (JSON.GET with JSONPath). Ideal when document size varies or you frequently update specific fields. Combine with RediSearch for full-text search within JSON documents. Use when application deals with JSON natively and you need efficient partial updates.

Sources
99% confidence
A

Redis replication uses asynchronous master-slave model. Master accepts writes immediately, forwards to replicas. Replicas replicate commands via TCP stream. Initial sync: RDB file + command buffer for changes during transfer. Replicas serve read-only queries. Commands: REPLICAOF host port to connect replica. Replication offset tracks sync position. Partial resynchronization possible (PSYNC). Replicas can be promoted to master. Redis 7+ supports replica-affected writes in cluster mode.

Sources
99% confidence
A

Redis replication guarantees: eventual consistency, high availability through replica promotion, read scaling. No strong consistency - recent writes may be lost if master fails. WAIT command blocks until N replicas acknowledge writes. Replication lag possible under heavy load. Network partitions can cause split-brain (two primaries). Automatic failover requires Redis Sentinel or Redis Cluster. Best effort durability - persists to replica async. Use WAIT for stronger guarantees when needed.

Sources
99% confidence
A

Redis Sentinel monitors Redis instances for high availability. Processes run separately from Redis servers. Features: health monitoring (ping checks), notification via pub/sub, automatic failover (promote replica to master), configuration provider (clients ask Sentinel for current master address). Requires odd number (3+) for quorum-based decisions. Uses distributed consensus. Sentinels communicate with each other and Redis instances. Can monitor multiple master-replica sets.

Sources
99% confidence
A

Sentinel HA workflow: monitors master/replica health via pings, detects failures through quorum voting (majority must agree master is down). On master failure: selects best replica (with lowest offset), promotes to master via SLAVEOF NO ONE, reconfigures other replicas to replicate from new master, notifies clients of topology change. Clients use Sentinel clients that automatically reconnect to new master. Provides automatic failover without Redis Cluster complexity. Suitable for smaller deployments needing HA.

Sources
99% confidence
A

Sorted sets characteristics: unique members (no duplicates), each member has associated score (double precision), automatically sorted by score (lexicographically if scores equal), O(log N) operations, up to 2^32-1 members, scores range from -inf to +inf. Supports both rank-based and score-based queries. Combines set uniqueness with ordering. Memory efficient for large collections. Can be used for time-series data (timestamp as score), leaderboards (score as performance metric), priority queues (score as priority).

Sources
99% confidence
A

Monitor Redis using: INFO command (comprehensive stats), SLOWLOG (slow queries log), MONITOR (real-time command monitoring, production caution), redis-cli --latency (latency histogram), redis-cli --stat (live stats dashboard). Key tools: Redis Insight (GUI), RedisGrafana dashboards, Prometheus redis_exporter. Application-level monitoring: track response times, error rates. External tools: Datadog, New Relic. Use CLIENT LIST to check connected clients. Monitor system metrics: CPU, memory, network.

Sources
99% confidence
A

Key Redis metrics: used_memory (RSS vs dataset size), connected_clients, instantaneous_ops_per_sec, keyspace_hits/(keyspace_hits+keyspace_misses) (hit rate), evicted_keys (memory pressure), expired_keys (TTL usage), blocked_clients, total_connections_received, total_commands_processed. Monitor slowlog entries (>10ms warning). Track replication lag for replicas. Important alerts: memory >80% maxmemory, hit rate <90%, evictions increasing, slowlog growing, client timeouts. Latency metrics: p50, p95, p99 response times.

Sources
99% confidence
A

HyperLogLog: probabilistic data structure for counting unique items with minimal memory. Uses 16384 6-bit registers (~12KB) regardless of cardinality. Standard error rate of 0.81%. Commands: PFADD key element (add element), PFCOUNT key (get count), PFMERGE dest key1 key2 (merge multiple HLLs). Based on hash of elements, leading zeros to estimate cardinality. Can process millions of unique items with constant memory. Can't retrieve individual elements - only count estimate available.

Sources
99% confidence
A

Use HyperLogLog for: counting unique visitors (websites, apps), tracking distinct IP addresses, unique search queries, user engagement metrics, distinct events in analytics, deduplication estimates. Perfect when exact count not required and memory is limited. Much more efficient than Sets for large cardinalities (Sets use memory per element, HLL uses constant 12KB). Use when you can accept ~1% error rate and don't need to retrieve the actual items. Ideal for analytics dashboards.

Sources
99% confidence
A

Redis bitmaps are bit arrays implemented using string data type. Each bit can be 0 or 1, addressed by offset (0-based). Commands: SETBIT key offset value, GETBIT key offset, BITCOUNT key [start end], BITOP operation destkey key1 key2, BITPOS key bit [start end]. Extremely space efficient: 1 byte stores 8 bits. Internally stored as compact string with automatic resizing. Can represent up to 2^32 bits (~512MB). Operations are O(1) for single bits, O(N) for range operations.

Sources
99% confidence
A

Bitmap use cases: user tracking (visited pages, feature flags), real-time analytics (active users per day), A/B testing (user group assignments), presence indicators (online/offline status), boolean flags per user entity, compact storage of binary data, counting active users with BITOP + BITCOUNT, finding first set bit with BITPOS. Perfect when you have many entities with boolean attributes. Example: 1 million users with daily login status = ~125KB. Use BITOP to calculate multiple-day activity patterns.

Sources
99% confidence
A

Avoid KEYS in production because it blocks the entire Redis server while scanning all keys. KEYS * processes O(N) where N is total keys, can freeze server for seconds or minutes with large datasets. All other client requests wait. Alternatives: SCAN cursor [MATCH pattern] [COUNT] for non-blocking iteration, or maintain separate index/set of keys. SCAN returns cursor incrementally, doesn't block, guarantees eventually all keys returned. Use SCAN for key exploration, cleanup scripts, debugging, analytics.

Sources
99% confidence
A

Avoid large values (>100KB) because Redis is single-threaded - large operations block other commands. Memory allocation overhead increases. Network transfer time increases latency. RDB snapshots take longer. Backup/restore times increase. Fragmentation becomes significant. Instead: break large data into multiple keys, use compression, store references instead of full data, or use external storage (S3, database) with Redis caching metadata. Keep values small (<10KB ideal) for optimal performance. Monitor memory fragmentation with INFO memory.

Sources
99% confidence
A

Always set TTL on cache entries to prevent memory leaks and stale data. Without TTL, cached data remains forever, consuming memory even when no longer needed. Cache entries typically become outdated over time. TTL ensures automatic cleanup of expired data. Set TTL based on data volatility: user sessions (hours), API responses (minutes), static content (days). Use EXPIRE key seconds or SETEX key seconds value. Redis automatically removes expired keys using active and passive eviction. Monitor expired_keys metric to understand TTL impact.

Sources
99% confidence
A

SCAN iterates keyspace using cursor-based iteration without blocking server. Basic usage: SCAN 0 (start), returns cursor + keys. Continue with returned cursor until cursor = 0 (complete). Options: MATCH pattern (filter keys), COUNT hint (suggested count). Returns array: [cursor, key1, key2, ...]. Guarantees: all keys present from start to end eventually returned, may return duplicates (caller dedupe), never blocks server. Works even during active data modifications. Also available: SSCAN (sets), HSCAN (hashes), ZSCAN (sorted sets).

Sources
99% confidence
A

Use SCAN over KEYS because SCAN doesn't block the server. KEYS * processes all keys in one operation, freezing Redis for all clients during iteration. SCAN processes keys incrementally, allowing other commands to execute between iterations. SCAN has constant time complexity per iteration, KEYS is O(N) all at once. SCAN can handle large datasets safely, KEYS risks server freeze. SCAN works even during key modifications. Use SCAN for production key iteration, cleanup scripts, debugging, analytics, and any operation requiring key enumeration.

Sources
99% confidence
A

RedisSearch is a search and indexing module in Redis Stack (Redis 7+) that provides full-text search, vector similarity search, and secondary indexing on Redis data. Enables real-time search with sub-millisecond latency. Includes FT.CREATE to define indexes, FT.SEARCH to query data. Supports hybrid queries combining text filters with vector search. No external search engine needed - everything runs within Redis for low-latency operations.

99% confidence
A

RedisSearch 2025 features: (1) Full-text search with stemming, fuzzy matching, phonetic search, prefix/phrase queries. (2) Vector similarity search using FLAT or HNSW indexes for embeddings. (3) Hybrid queries combining text filters with vector KNN search. (4) Aggregations pipeline (FT.AGGREGATE) for analytics. (5) Secondary indexes on TEXT, TAG, NUMERIC, GEO, GEOSHAPE, VECTOR fields. (6) Auto-complete suggestions. (7) Scales to billion+ vectors with <10ms latency. Performance: 18x faster than Elasticsearch for vector workloads.

99% confidence
A

Create full-text index with FT.CREATE: FT.CREATE idx:products ON HASH PREFIX 1 'product:' SCHEMA name TEXT SORTABLE description TEXT price NUMERIC category TAG SORTABLE. Then add data: HSET product:1 name 'Laptop' description 'Gaming laptop' price 1200 category 'electronics'. Query: FT.SEARCH idx:products 'gaming laptop' returns matching products. TEXT enables full-text search with stemming. TAG for exact matching. NUMERIC for range filters. SORTABLE enables sorting. Indexes update automatically when data changes.

99% confidence
A

Create vector index: FT.CREATE idx:embeddings ON HASH PREFIX 1 'doc:' SCHEMA embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 384 DISTANCE_METRIC COSINE. Add vectors: HSET doc:1 embedding . Query with KNN: FT.SEARCH idx:embeddings '*=>[KNN 10 @embedding $query_vec]' PARAMS 2 query_vec DIALECT 2. HNSW provides fast approximate search (vs FLAT exact search). Supports L2, IP, COSINE distance metrics. Hybrid queries: combine vector KNN with filters. Scales to billion+ vectors at single-digit ms latency.

99% confidence
A

RedisSearch solves: slow pattern matching (vs KEYS/SCAN), missing full-text search capabilities, complex query requirements, real-time search needs, filtering by non-key attributes, aggregations on Redis data, auto-complete functionality, geospatial queries with text search. Alternative to Elasticsearch for simpler use cases where you already use Redis. Much faster than SCAN + client-side filtering. Provides search capabilities without external service dependency. Reduces system complexity by keeping search within Redis.

Sources
99% confidence
A

Implement distributed locks using SET command with NX (only if not exists) and EX (expire) options: SET lock_key unique_value NX EX 30. unique_value (UUID) identifies lock owner. To release: Lua script checks value matches then DEL: if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0. For high availability, use Redlock algorithm across multiple Redis instances (5+ recommended). Extend TTL before expiry if operation still in progress. Avoid long-held locks (>30 seconds).

Sources
99% confidence
A

Redis geospatial indexes store longitude/latitude coordinates using sorted sets internally with Geohash encoding. Commands: GEOADD key longitude latitude member (add location), GEORADIUS key longitude latitude radius unit (find points within radius), GEORADIUSBYMEMBER key member radius unit (find points near existing member), GEOPOS key member (get coordinates), GEODIST member1 member2 unit (calculate distance). Units: meters (m), kilometers (km), miles (mi), feet (ft). Supports WITHDIST, WITHCOORD, WITHHASH options in queries for additional data.

Sources
99% confidence
A

Use geospatial indexes for: finding nearby locations (stores within 5km), location-based search, delivery routing, proximity alerts, geofencing, location-aware features. Example workflow: GEOADD stores -122.4194 37.7749 'store1', then GEORADIUS stores -122.4194 37.7749 10 km WITHDIST WITHCOORD. Perfect for ride-sharing, food delivery, social apps, asset tracking. Use WITHDIST to include distance, WITHCOORD for coordinates, COUNT N to limit results. Combine with other Redis data types for complex location-based queries.

Sources
99% confidence
A

Connection pooling reuses TCP connections instead of creating new ones per operation. Pool maintains set of open connections, checks them out/in for use. Eliminates TCP handshake overhead (3-way handshake, TLS negotiation). Reduces server resource usage (fewer sockets, less context switching). Most Redis clients include built-in pooling support. Pools manage connection lifecycle: creation, validation, idle timeout, removal. Can configure min/max pool size, connection lifetime, idle timeouts.

Sources
99% confidence
A

Connection pooling important because: reduces latency (no handshake per operation), prevents connection exhaustion (server socket limits), improves throughput, reduces CPU overhead, enables concurrent request handling. Without pooling, each Redis operation creates new connection -> high overhead, slow performance, server strain. Essential for web applications with concurrent requests. Without pooling, you'll see connection errors, performance degradation under load. Critical for production environments handling multiple simultaneous Redis operations.

Sources
99% confidence
A

Redis (REmote DIctionary Server) is an in-memory data structure store used as database, cache, message broker, and streaming engine. Single-threaded with I/O multiplexing for millisecond-level latency. Redis 8 (GA 2025) supports 15+ data structures: strings, hashes, lists, sets, sorted sets, streams, JSON, vector sets (beta), time series, geospatial indexes, bitmaps, HyperLogLog, and probabilistic structures (Bloom filters, cuckoo filters, t-digest, top-k, count-min sketch). Persistence via RDB snapshots or AOF (append-only file). Stores all data in RAM with optional disk persistence. Horizontal scaling via Redis Cluster (16384 hash slots). High availability through replication and Redis Sentinel.

99% confidence
A

Redis primary use cases: caching (sub-millisecond latency), session storage, real-time analytics, rate limiting, leaderboards, pub/sub messaging, job queues, geospatial queries, time-series data, user tracking, message queuing, event streaming. Excellent for high-performance scenarios requiring low latency data access. Common in web applications for session management, in e-commerce for shopping carts, in gaming for leaderboards, and in analytics for real-time dashboards.

Sources
99% confidence
A

Redis Strings: simple key-value binary data, maximum 512MB per string. Binary-safe (can store images, serialized objects). Commands: SET/GET, INCR/DECR, APPEND, MGET, STRLEN. Atomic operations on single keys. Can store integers (up to 2^63) with atomic increment/decrement. Memory efficient for small values. Used as building blocks for other data types. Most basic Redis data type, supports bit operations (GETBIT, SETBIT, BITCOUNT).

99% confidence
A

Use Redis Strings for: caching values, counters (page views, API limits), session storage, rate limiting, configuration values, simple flags, binary data storage. Perfect for atomic counters (INCR, DECR operations). Store JSON blobs, user sessions, cached database results. Use when you need simple key-value storage with optional atomic increment operations. Not ideal for complex nested data - use Hashes instead.

99% confidence
A

Redis Lists: ordered collections of strings, implemented as linked lists. Commands: LPUSH/RPUSH (add to ends), LPOP/RPOP (remove from ends), LRANGE (get range), LTRIM (trim), LLEN (length). O(1) operations at ends, O(N) for middle access. Can block with BLPOP/BRPOP for queue semantics. Max length 2^32-1 elements. Each element up to 512MB. Maintains insertion order. Can be used as both queue and stack.

99% confidence
A

Use Redis Lists for: queues (job processing), stacks, activity feeds, recent items lists with LTRIM, message queues, timeline feeds. Perfect for producer-consumer patterns with BLPOP/BRPOP. Use when you need to process items in FIFO or LIFO order. Not ideal for random access by index - use Sets or Sorted Sets instead. Excellent for background job queues where workers process tasks in order.

99% confidence
A

Redis Sets: unordered collections of unique strings, O(1) operations for all basic operations. Commands: SADD (add), SREM (remove), SMEMBERS (all members), SISMEMBER (check membership), SCARD (size), SUNION (union), SINTER (intersection). Guarantees uniqueness - duplicate additions ignored. Can store up to 2^32-1 elements. Membership testing is extremely fast. Not ordered - if order matters, use Sorted Sets.

99% confidence
A

Use Redis Sets for: unique visitors tracking, tag systems, preventing duplicates, relationships (followers/following), shared interests, access control lists, inventory management. Perfect when uniqueness matters and you need fast membership testing. Use SINTER for common elements (users who liked both X and Y). Use SUNION for combining sets. Not suitable when order matters or you need associated scores.

99% confidence
A

Redis Hashes: field-value pairs within a single key, storing small objects. Commands: HSET/HGET (set/get field), HMGET/HMSET (multiple fields), HGETALL (all fields), HDEL (delete field), HEXISTS (field exists). Each hash can store up to 2^32-1 fields, each field up to 512MB. Memory efficient for small objects. Fields within hash don't have TTL individually. Think of as Redis version of a row or document.

99% confidence
A

Use Redis Hashes for: user profiles, configuration objects, caching database rows, product attributes, session data with multiple fields. Perfect when you need multiple related fields for one entity. More memory efficient than multiple top-level keys. Use HGETALL to retrieve entire object. Not ideal for very large objects (>10KB) or when you need individual field TTL. Use when you frequently access the entire object together.

99% confidence
A

Sets store unique values without additional data; Hashes store field-value pairs. Sets: SADD value, SISMEMBER value. Hashes: HSET field value, HGET field. Sets guarantee uniqueness and support set operations (union, intersection). Hashes store structured data like objects. Use Sets for uniqueness checks and collections; use Hashes for structured objects. Sets have no ordering; Hashes have field names (but no guaranteed ordering). Both provide O(1) operations.

99% confidence
A

Redis Sorted Sets: ordered collections of unique strings with associated scores (double-precision floating point). Maintained in score order with O(log N) operations. If scores equal, sorted lexicographically. Commands: ZADD (add with score), ZRANGE (by rank), ZRANGEBYSCORE (by score range), ZRANK (get rank), ZSCORE (get score), ZINCRBY (increment score). Max 2^32-1 members per sorted set. Most powerful Redis data structure for queries.

99% confidence
A

Redis Sorted Sets use cases: leaderboards (gaming scores with ZINCRBY user 1), priority queues (task scheduling with scores as priority), time-series data (timestamps as scores), rate limiting windows (activity timestamps), range queries (price ranges with ZRANGEBYSCORE), sliding windows (expire old entries), weighted rankings, auto-complete suggestions, capacity planning, resource scheduling. Perfect for anything requiring ranking or time-based ordering.

99% confidence
A

Cache-Aside (Lazy Loading): application checks cache first; on miss, fetches from database, then writes to cache. Application controls both cache and database directly. Implementation flow: 1) Try cache GET, 2) If miss, query database, 3) Write result to cache with TTL, 4) Return data. Best for read-heavy workloads where data changes occasionally. Most common Redis caching pattern due to simplicity and control.

99% confidence
A

Use Cache-Aside for: read-heavy applications, user-generated content, product catalogs, user profiles, session data. Advantages: only requested data gets cached, resilient to cache failures. Disadvantages: cache miss penalty (3 round trips), potential stale data, requires cache warming. Avoid for write-heavy workloads or real-time data requirements. Best when you can tolerate slight staleness and want to minimize cache size by storing only frequently accessed data.

99% confidence
A

RDB (Redis Database) creates point-in-time snapshots of the entire dataset at configured intervals. Generates compact single files with .rdb extension. Configuration: save 900 1 (if 1+ keys changed in 900s), save 300 10, save 60 10000. Snapshots are binary representations of memory state. Redis forks process to create snapshot without blocking operations. Files portable across Redis versions. Can be used for backups and migration.

Sources
99% confidence
A

Use RDB for: development environments, backup strategies, scenarios where occasional data loss is acceptable, fast recovery needs, disaster recovery. Excellent when backup portability and fast restarts are priorities. Redis 7+ uses hybrid RDB-AOF format combining benefits. Avoid for mission-critical data requiring maximum durability. Choose when restart speed matters more than minimal data loss, and when you can tolerate losing recent changes (between snapshots).

Sources
99% confidence
A

AOF (Append Only File) logs every write operation to provide maximum durability. Configurable fsync policies: always (every write, slowest), everysec (default, good balance), no (fastest, highest data loss risk). Files larger than RDB but provide append-only guarantee (no corruption). Redis 7+ uses optimized RDB-AOF format. Can be rewritten to minimize file size. Contains sequential log of all write commands needed to rebuild dataset state.

Sources
99% confidence
A

AOF ensures durability by appending every write command to file before acknowledging operation. With appendfsync everysec (default), Redis fsyncs every second - balances performance and durability. On restart, Redis replays all logged operations to rebuild exact state. No data corruption due to append-only nature. Can survive crashes with minimal data loss (max 1 second with everysec policy). Redis 7+ reduces restart time with hybrid RDB-AOF format.

Sources
99% confidence
A

Redis expiration policies: passive (checked on key access) and active (random sampling, evicts expired). Passive: when key accessed, check if expired. Active: every 100ms, randomly test 20 keys, delete expired ones, and if expired keys > 25%, repeat. This hybrid approach balances memory usage and CPU overhead. Works even if keys never accessed after expiration. TTL persists across save/reload (RDB saves expiration times, AOF logs DEL commands).

Sources
99% confidence
A

TTL (Time To Live) sets key expiration in seconds or milliseconds. Commands: EXPIRE key seconds, PEXPIRE key milliseconds, TTL key (remaining seconds), PTTL key (milliseconds). Set with creation: SET key value EX 3600 or SETEX. Remove with PERSIST. Once expired, key is automatically deleted. TTL precision is milliseconds but stored as integer milliseconds. Returns -1 if no expiration, -2 if key doesn't exist. Atomic operations with TTL maintain consistency.

Sources
99% confidence
A

Redis eviction policies when maxmemory reached: noeviction (return errors, default), allkeys-lru (evict least recently used), allkeys-lfu (least frequently used), allkeys-random (random eviction), volatile-lru (only keys with TTL), volatile-lfu (TTL + LFU), volatile-random (TTL + random), volatile-ttl (shortest TTL first). Policies with 'volatile' only consider keys with expiration set. Set with CONFIG SET maxmemory-policy policy_name. Different memory management strategies for different use cases.

Sources
99% confidence
A

Use allkeys-lru for general caching scenarios - approximates real access patterns. Use volatile-lru when mixing cache and persistent data - only evicts temporary cache entries. Use allkeys-lfu for hot data patterns - keeps frequently accessed items regardless of recent access. Use volatile-ttl for session data - evicts closest to expiration. Use noeviction for database-like scenarios where data loss unacceptable. Choose based on data characteristics and access patterns.

Sources
99% confidence
A

Redis transactions queue commands with MULTI, execute atomically with EXEC. Commands are queued but not executed until EXEC. EXEC processes all queued commands sequentially without interruption from other clients. DISCARD cancels transaction. All commands processed or none (server crash). Transaction doesn't roll back on individual command failures - successful commands still execute. No isolation like SQL - other clients can read data during transaction (but not modify queued keys).

Sources
99% confidence
A

Redis transaction guarantees: all commands processed sequentially without interruption, all-or-nothing execution (if server crashes during EXEC, no commands applied). No automatic rollback on errors - individual command failures don't stop execution. WATCH provides optimistic locking (check-and-set) - if watched keys modified before EXEC, transaction fails. Basic atomicity and ordering guaranteed, but not full ACID properties. Use Lua scripts for more complex atomic operations with better error handling.

Sources
99% confidence
A

Redis Pub/Sub provides publish/subscribe messaging with channels. Publishers send messages with PUBLISH channel message. Subscribers receive messages with SUBSCRIBE channel. Pattern subscription with PSUBSCRIBE for multiple channels. Fire-and-forget pattern - messages not persisted, lost if no subscribers active. Low latency messaging with minimal overhead. Up to 2^32-1 channels. Messages delivered to all active subscribers (broadcast). No message persistence or delivery guarantees.

Sources
99% confidence
A

Pub/Sub workflow: Clients SUBSCRIBE to channels, become blocking receivers. Publishers PUBLISH messages to channels, all active subscribers immediately receive. Redis maintains active subscriptions in memory. Messages delivered in order received. No queuing for offline subscribers. PSUBSCRIBE matches patterns (user:, news:tech). UNSUBSCRIBE removes subscriptions. Client can subscribe to multiple channels simultaneously. Subscriptions survive connection drops if client reconnects.

Sources
99% confidence
A

Redis Streams provide persistent, append-only logs with consumer groups. Each entry has unique ID (timestamp-sequence). Commands: XADD stream * field value (append entry), XREAD COUNT streams stream $ (read from end), XRANGE (range queries). Entries stored indefinitely unless trimmed (XTRIM). Supports length-based and time-based trimming. Each entry can have multiple fields. Auto-generated IDs ensure chronological ordering. Can store up to 2^64-1 entries per stream.

Sources
99% confidence
A

Redis Streams reliability: consumer groups with XGROUP CREATE stream group $ (starting from new entries) or 0 (from beginning). XREADGROUP GROUP stream consumer COUNT streams (read messages). XACK acknowledges processing. PEL (Pending Entries List) tracks unacknowledged messages. Consumers claim stale entries with XCLAIM. At-least-once delivery guaranteed. No message loss if consumer crashes - messages remain in PEL. Can reprocess failed messages. Consumer groups allow load distribution across multiple consumers.

Sources
99% confidence
A

Redis Cluster partitions data across 16384 hash slots. Each slot assigned to a master node. CRC16(key) mod 16384 determines slot. Hash tags {} force keys to same slot: {user:123}:profile and {user:123}:orders. Client library routes commands to correct node. Automatic rebalancing when adding/removing nodes. Minimum 3 masters for high availability (with optional replicas). No cross-slot operations (except Lua scripts with keys in same slot). Eventually consistent model.

Sources
99% confidence
A

Redis Cluster characteristics: horizontal scaling beyond single server RAM limits, automatic failover with replica promotion, high availability with master-replica topology, client-side routing (no proxy bottleneck), eventual consistency, minimum 3 master nodes recommended. Trade-offs: no multi-key operations across hash slots, requires cluster-aware client libraries, complex deployment and monitoring. Best for large datasets (>50GB) and high availability requirements where single-node limitations become bottleneck.

Sources
99% confidence
A

Pipelining sends multiple commands without waiting for responses, reducing round-trip time (RTT). Client buffers commands, sends batch to server, server processes sequentially, returns all responses. Commands executed in order sent. Not atomic - other clients' commands may interleave. Most Redis clients support pipelining with flush/execute methods. Different from MULTI/EXEC: no atomicity guarantees, just performance optimization. Reduces network latency impact significantly.

Sources
99% confidence
A

Pipelining improves performance by reducing network round-trips. Without pipelining: command send -> wait -> receive -> repeat (N RTTs). With pipelining: send N commands -> receive N responses (1 RTT). Performance gain proportional to network latency - 10x+ throughput on high-latency networks. Memory overhead: client buffers responses for all pipelined commands. Best for bulk operations like data import/export, batch processing, MGET/MSET with multiple keys. Combine with transactions for atomic batching when needed.

Sources
99% confidence
A

EVAL command executes Lua scripts on Redis server. Scripts access Redis via redis.call() (errors propagate) or redis.pcall() (returns errors). EVALSHA executes cached scripts by SHA1 hash. Scripts must be deterministic (no random numbers, time, external calls). Can accept parameters, return values. Scripts execute atomically - no other commands interleaved. Server can cache compiled scripts. Script execution time limited (configurable SCRIPT_TIMEOUT).

Sources
99% confidence
A

Lua script advantages: atomic execution (no interleaving with other commands), reduces round trips (complex logic on server), access to all Redis commands, better performance than client-side logic, conditional operations (if-then), read-modify-write patterns, complex data transformations. More powerful than MULTI/EXEC for complex workflows. Scripts can be reused and cached by SHA1. Essential for implementing custom data structures, complex business logic, and ensuring consistency across multiple operations.

Sources
99% confidence