Polygon Technology

Mastering Redis: From Core Data Types to Redis Stack & AI Search

Mastering Redis: From Core Data Types to Redis Stack & AI Search

Master Redis, basics to advanced scaling. Covering core data structures, caching, and Redis Stack’s JSON, search, & AI features.
Backend Development
February 5, 2026
Ashfat Al Rashid
Ashfat Al Rashid

SQA Engineer specializing in backend testing, API automation (RestAssured, Postman), and test automation with Java. Proficient in UI automation (Selenium, POM) and performance testing (JMeter). Experienced in manual, regression, database, and UAT testing, ensuring software quality across various platforms.

Md. Asad Chowdhury Dipu

Redis is an open-source, in-memory data structure store widely used as a database, cache, and message broker. Its speed, flexibility, and rich feature set make it a core component in modern backend architectures. Redis was developed by Italian computer programmer Salvatore Sanfilippo, also known by his online handle “antirez,” starting in 2009 to solve scalability issues for his startup.

This blog will take you on a journey from basic Redis concepts to advanced, real-world usage patterns, with practical explanations tailored for backend and full-stack developers.

1. What is Redis?

Redis is an in-memory key–value store, meaning data is primarily stored in RAM instead of disk. This allows Redis to achieve extremely low latency (often sub-millisecond).

Key Characteristics

  • In-memory (with optional persistence)
  • Single-threaded command execution (with multi-threaded I/O in modern Redis)
  • Supports multiple data structures
  • Built-in replication and clustering
  • Used for caching, real-time analytics, queues, sessions, and more

2. Why Use Redis?

Common Use Cases

  • Caching (API responses, DB queries)
  • Session storage (JWT/session-based auth)
  • Rate limiting
  • Real-time counters & leaderboards
  • Pub/Sub messaging
  • Background job queues

Redis vs Traditional Databases

Feature
Redis
SQL/NoSQL DB
Storage
Memory-first
Disk-first
Speed
Extremely fast
Slower
Data Types
Rich
Limited
Persistence
Optional
Mandatory

3. Redis Installation & Basics

Installing Redis

sudo apt install redis

redis-server

Redis CLI

redis-cli

PING

# PONG

Redis stores data as key → value pairs.

4. Core Redis Data Types

4.1 Strings

The simplest and most commonly used type.

SET key value

GET key

4.2 Lists

Ordered collections (like arrays or queues).

LPUSH tasks "task1"
RPUSH tasks "task2"
LPOP tasks

Use cases:

  • Job queues
  • Message buffering

4.3 Sets

Unordered collections of unique values.

SADD online_users user1 user2

SISMEMBER online_users user1 

SMEMBERS online_users

Use cases:

  • Tracking unique users
  • Tags

4.4 Hashes

Key–value pairs inside a single Redis key.

HSET user:1 name "John" age 25

HGETALL user:1

Use cases:

  • User profiles

  • Config objects

5. Key Expiration (TTL)

Redis supports automatic expiration of keys.

SET otp:1234 "999999" EX 60

TTL otp:1234

Use cases:

  • OTPs

  • Session expiration

  • Cache invalidation

6. Pub/Sub Messaging

Redis supports real-time message broadcasting.

Publisher

PUBLISH notifications "User logged in"

Subscriber

SUBSCRIBE notifications

Use cases:

  • Real-time notifications
  • Chat systems

7. Redis as a Cache (Cache-Aside Pattern)

Flow:

  • App checks Redis
  • Cache hit → return data
  • Cache miss → fetch from DB
  • Store in Redis
const cached = await redis.get(key);

if (!cached) {

const data = await db.find();

await redis.set(key, JSON.stringify(data), 'EX', 300);

8. Persistence (RDB & AOF)

RDB (Snapshotting)

  • Periodic snapshots
  • Faster startup
  • Possible data loss

AOF (Append Only File)

  • Logs every write
  • Safer
  • Slightly slower

Best practice: Enable both.

9. Redis Transactions

Redis supports atomic operations using MULTI.

MULTI

INCR balance

DECR stock

EXEC

N.B: Redis transactions guarantee atomic execution but do not support rollback. If one command fails, others still execute. For strict atomic logic, use Lua scripting.

10. Lua Scripting

Lua scripts execute atomically inside Redis.

EVAL "return redis.call('INCR', KEYS[1])" 1 counter

Use cases:

  • Rate limiting
  • Complex atomic logic

11. Rate Limiting with Redis

Using counters + TTL:

INCR user:1:requests

EXPIRE user:1:requests 60 NX

Or using Lua for accuracy

12. Redis Streams (Advanced Messaging)

Streams are append-only logs.

XADD orders * user_id 1 amount 200

XREAD COUNT 10 STREAMS orders 0

Use cases:

  • Event sourcing
  • Distributed systems
  • Kafka-like pipelines

13. Redis Stack & RediSearch (Advanced Querying in Redis)

While traditional Redis excels at fast key-based access, it does not support SQL-like queries such as filtering, searching, or aggregation. Redis Stack extends Redis with powerful modules—most notably RediSearch, which enables advanced querying and indexing.

What Is Redis Stack?

Redis Stack is an enhanced Redis distribution that includes:

  • RediSearch (search & indexing)
  • RedisJSON (JSON document storage)
  • RedisBloom (probabilistic data structures)
  • RedisTimeSeries (time-series data)

With Redis Stack, Redis evolves from a key–value store into a real-time search and analytics engine.

13.1 Why RediSearch?

RediSearch enables:

  • Full-text search
  • Numeric range queries
  • Tag-based filtering
  • Sorting & pagination
  • Aggregations (GROUP BY, COUNT, AVG)
  • Vector similarity search (AI / semantic search)

This allows Redis to handle many use cases traditionally reserved for SQL or Elasticsearch—but with Redis-level performance.

13.2 Indexing Data in Redis

RediSearch works by creating indexes on Redis data (Hashes or JSON).

Hash Example

HSET user:1 name "John Doe" age 32 role admin salary 5000

Create an index:

FT.CREATE users_idx

ON HASH

PREFIX 1 user:

SCHEMA

name TEXT

role TAG

age NUMERIC

salary NUMERIC SORTABLE

13.3 Querying with RediSearch

Full-text search

FT.SEARCH users_idx "John"

Filter by tag

FT.SEARCH users_idx "@role:{admin}"

Numeric range

FT.SEARCH users_idx "@age:[30 40]"

Combined conditions (AND)

FT.SEARCH users_idx "@role:{admin} @age:[30 40]"

Pagination

FT.SEARCH users_idx "*" LIMIT 0 10

13.4 Aggregations (Analytics)

Count users by role:

FT.AGGREGATE users_idx "*"

GROUPBY 1 @role

REDUCE COUNT 0 AS total

Average salary per role:

FT.AGGREGATE users_idx "*"

GROUPBY 1 @role

REDUCE AVG 1 @salary AS avg_salary

This makes Redis suitable for real-time dashboards and analytics.

13.5 RedisJSON + RediSearch

Redis Stack supports indexing JSON documents:

JSON.SET user:2 $ '{

"name": "Alice",

"age": 29,

"role": "manager"

}'

Index JSON fields:

FT.CREATE users_json_idx

ON JSON

PREFIX 1 user:

SCHEMA

$.name AS name TEXT

$.role AS role TAG

$.age AS age NUMERIC

13.6 Vector Search (AI & RAG Use Cases)

RediSearch supports vector similarity search:

  • Semantic search
  • Chatbots
  • Recommendation systems
FT.CREATE docs_idx

ON HASH

SCHEMA

content TEXT

embedding VECTOR HNSW 1536 TYPE FLOAT32 DISTANCE_METRIC COSINE
13.7 When to Use Redis StackUse Redis Stack when you need:
  • Fast search with filtering
  • Real-time analytics
  • User search & dashboards
  • AI-powered retrieval (RAG)
Avoid it for:
  • Heavy relational joins
  • Large cold-storage datasets
Mental ModelRedis Core → Key-based accessRedis Stack → Search engine + cache + real-time databaseRedis Stack complements—not replaces—traditional databases.

14. Redis in Production (Best Practices)

  • Set maxmemory limits
  • Choose eviction policy (LRU, LFU)
  • Use connection pooling
  • Avoid large keys
  • Monitor with Redis Insight

15. When NOT to Use Redis

  • Large persistent datasets
  • Complex relational queries
  • Strong consistency requirements

HSET user:1 name "John Doe" age 32 role admin salary 5000

Create an index:

FT.CREATE users_idx

ON HASH

PREFIX 1 user:

SCHEMA

name TEXT

role TAG

age NUMERIC

salary NUMERIC SORTABLE

Conclusion

Redis starts as a simple key–value store but evolves into a powerful distributed system component when used correctly. From caching and sessions to streams and clustering, Redis plays a crucial role in scalable backend architecture.If you master Redis fundamentals and advanced concepts, you gain a major advantage in building high-performance, real-time applications.