What is Redis? And its Showcase Use

Estimated read time 11 min read

Redis (short for REmote DIctionary Server) is an open-source, in-memory data structure store used as a database, cache, message broker, and streaming engine. It is known for its high performance, low latency, and versatility.

Key Features of Redis:

  1. In-memory Storage:
    • Redis keeps all data in RAM, enabling extremely fast read and write operations.
  2. Data Structures:
    • Redis supports various data types:
      • Strings
      • Lists
      • Sets
      • Hashes
      • Sorted sets
      • Bitmaps
      • HyperLogLogs
      • Streams
      • Geospatial indexes
  3. Persistence:
    • Although it’s in-memory, Redis supports persistence to disk using:
      • RDB (Redis Database Backups) – point-in-time snapshots.
      • AOF (Append-Only File) – logs every write operation.
  4. Pub/Sub:
    • Built-in publish/subscribe messaging allows message broadcasting and listening between services.
  5. Atomic Operations:
    • Most commands are atomic, meaning multiple clients won’t interfere with each other’s operations.
  6. Replication and Clustering:
    • Supports master-slave replication and clustering for horizontal scalability and high availability.
  7. Use Cases:
    • Caching (e.g., session storage)
    • Real-time analytics
    • Leaderboards
    • Message queues
    • Rate limiting
    • Chat systems
  8. Programming Language Support:
    • Redis has clients for almost every programming language (Python, Java, Node.js, Go, etc.).

Example Use Case:

To cache user session data:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('session:user123', 'data', ex=3600)  # Expires in 1 hour

Redis is widely used in high-performance applications due to its speed, rich data structures, and simplicity. It’s often used alongside traditional databases to reduce latency and increase throughput.

What is Application showcase with this Redis?

An application showcase using Redis typically refers to a real-world or demo application that demonstrates how Redis can be effectively integrated to improve performance, scalability, or functionality. Below are some example showcases across various use cases:

1. Real-Time Chat Application

Redis Features Used:

  • Pub/Sub (for sending/receiving messages instantly)
  • Lists (message queues)
  • Hashes (user session storage)

Purpose:

  • Achieve low-latency communication
  • Store chat history temporarily
  • Track online users

Example:

  • A Slack-like app where channels and DMs use Redis Pub/Sub to deliver messages in real-time.

2. High-Performance Caching Layer

Redis Features Used:

  • Strings (key-value store)
  • TTL (expiration)

Purpose:

  • Reduce load on the primary database
  • Speed up API responses
  • Improve scalability

Example:

  • An e-commerce site caches product data or search results in Redis to reduce PostgreSQL queries.

3. Leaderboard System for Games

Redis Features Used:

  • Sorted Sets

Purpose:

  • Maintain real-time rankings based on player scores

Example:

  • A mobile game app shows the top 100 players, updated in real-time as scores change.

4. Rate Limiting API Requests

Redis Features Used:

  • Strings or Sorted Sets
  • TTL / Expiry

Purpose:

  • Prevent abuse by limiting how often a user can hit an API

Example:

  • A REST API limits each user to 100 requests per minute using Redis counters and expiration logic.

5. Real-Time Analytics Dashboard

Redis Features Used:

  • Streams
  • HyperLogLog (for approximate counts)

Purpose:

  • Aggregate and show user actions, page views, etc., in near real-time

Example:

  • A dashboard that tracks website visits per second and displays real-time graphs.

6. Session Management

Redis Features Used:

  • Strings or Hashes
  • Expiry

Purpose:

  • Store session data for logged-in users

Example:

  • A web application (e.g., Django or Express.js) uses Redis to store session tokens and user info.

7. Shopping Cart System

🔧 Redis Features Used:

  • Hashes (for cart items)
  • Expiry (to auto-remove abandoned carts)

Purpose:

  • Manage user carts in a fast and transient manner

Example:

  • An online store keeps each user’s cart in Redis for quick access during checkout.

Programming Examples using Golang, PHP, and Python to showcase how to use various Redis data structures.

SETUP:

  • Redis server must be running (default port: 6379)
  • Redis client library installed in each language

🐍 PYTHON (using redis-py)

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# Strings
r.set('name', 'Alice')
print(r.get('name'))  # b'Alice'

# Lists
r.rpush('tasks', 'task1', 'task2')
print(r.lrange('tasks', 0, -1))  # [b'task1', b'task2']

# Sets
r.sadd('tags', 'python', 'golang', 'php')
print(r.smembers('tags'))

# Hashes
r.hset('user:1000', mapping={'name': 'Bob', 'age': 30})
print(r.hgetall('user:1000'))

# Sorted Sets
r.zadd('leaderboard', {'Alice': 100, 'Bob': 200})
print(r.zrange('leaderboard', 0, -1, withscores=True))

# Bitmaps
r.setbit('user_flags', 7, 1)
print(r.getbit('user_flags', 7))  # 1

# HyperLogLog
r.pfadd('visitors', 'user1', 'user2')
print(r.pfcount('visitors'))

# Streams
r.xadd('mystream', {'user': 'alice', 'action': 'login'})
print(r.xrange('mystream', '-', '+'))

🐘 PHP (using predis/predis via Composer)

<?php
require 'vendor/autoload.php';

$redis = new Predis\Client();

// Strings
$redis->set('name', 'Alice');
echo $redis->get('name');

// Lists
$redis->rpush('tasks', ['task1', 'task2']);
print_r($redis->lrange('tasks', 0, -1));

// Sets
$redis->sadd('tags', ['php', 'python', 'golang']);
print_r($redis->smembers('tags'));

// Hashes
$redis->hmset('user:1000', ['name' => 'Bob', 'age' => 30]);
print_r($redis->hgetall('user:1000'));

// Sorted Sets
$redis->zadd('leaderboard', ['Alice' => 100, 'Bob' => 200]);
print_r($redis->zrange('leaderboard', 0, -1, ['withscores' => true]));

// Bitmaps
$redis->setbit('user_flags', 7, 1);
echo $redis->getbit('user_flags', 7);

// HyperLogLog
$redis->pfadd('visitors', ['user1', 'user2']);
echo $redis->pfcount('visitors');

// Streams
$redis->xadd('mystream', '*', ['user' => 'alice', 'action' => 'login']);
print_r($redis->xrange('mystream', '-', '+'));

🦫 GOLANG (using github.com/redis/go-redis/v9)

package main

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func main() {
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	// Strings
	rdb.Set(ctx, "name", "Alice", 0)
	name, _ := rdb.Get(ctx, "name").Result()
	fmt.Println("Name:", name)

	// Lists
	rdb.RPush(ctx, "tasks", "task1", "task2")
	tasks, _ := rdb.LRange(ctx, "tasks", 0, -1).Result()
	fmt.Println("Tasks:", tasks)

	// Sets
	rdb.SAdd(ctx, "tags", "golang", "python", "php")
	tags, _ := rdb.SMembers(ctx, "tags").Result()
	fmt.Println("Tags:", tags)

	// Hashes
	rdb.HSet(ctx, "user:1000", "name", "Bob", "age", 30)
	user, _ := rdb.HGetAll(ctx, "user:1000").Result()
	fmt.Println("User:", user)

	// Sorted Sets
	rdb.ZAdd(ctx, "leaderboard", redis.Z{Score: 100, Member: "Alice"}, redis.Z{Score: 200, Member: "Bob"})
	leaders, _ := rdb.ZRangeWithScores(ctx, "leaderboard", 0, -1).Result()
	fmt.Println("Leaderboard:", leaders)

	// Bitmaps
	rdb.SetBit(ctx, "user_flags", 7, 1)
	bit, _ := rdb.GetBit(ctx, "user_flags", 7).Result()
	fmt.Println("Bit 7:", bit)

	// HyperLogLog
	rdb.PFAdd(ctx, "visitors", "user1", "user2")
	count, _ := rdb.PFCount(ctx, "visitors").Result()
	fmt.Println("Visitor count:", count)

	// Streams
	rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: "mystream",
		Values: map[string]interface{}{"user": "alice", "action": "login"},
	})
	streams, _ := rdb.XRange(ctx, "mystream", "-", "+").Result()
	fmt.Println("Stream:", streams)
}

C++ Programming with Redis – Prerequisites

  1. Install Redis server (if not already): sudo apt install redis-server
  2. Install hiredis (C client library): sudo apt install libhiredis-dev
  3. Compile with: g++ -o redis_demo redis_demo.cpp -lhiredis

redis_demo.cpp — Showcase of Redis Data Types in C++

#include <iostream>
#include <hiredis/hiredis.h>

void checkReply(redisReply* reply) {
    if (!reply) {
        std::cerr << "Error: No reply\n";
        exit(1);
    }
}

int main() {
    redisContext* c = redisConnect("127.0.0.1", 6379);
    if (c == NULL || c->err) {
        std::cerr << "Connection error: " << (c ? c->errstr : "can't allocate redis context") << "\n";
        return 1;
    }

    redisReply* reply;

    // String
    reply = (redisReply*)redisCommand(c, "SET name Alice");
    checkReply(reply); freeReplyObject(reply);
    reply = (redisReply*)redisCommand(c, "GET name");
    std::cout << "String - name: " << reply->str << "\n"; freeReplyObject(reply);

    // List
    redisCommand(c, "DEL tasks");
    redisCommand(c, "RPUSH tasks task1 task2");
    reply = (redisReply*)redisCommand(c, "LRANGE tasks 0 -1");
    std::cout << "List - tasks:\n";
    for (size_t i = 0; i < reply->elements; ++i)
        std::cout << "- " << reply->element[i]->str << "\n";
    freeReplyObject(reply);

    // Set
    redisCommand(c, "SADD tags cpp python redis");
    reply = (redisReply*)redisCommand(c, "SMEMBERS tags");
    std::cout << "Set - tags:\n";
    for (size_t i = 0; i < reply->elements; ++i)
        std::cout << "- " << reply->element[i]->str << "\n";
    freeReplyObject(reply);

    // Hash
    redisCommand(c, "HSET user:1000 name Bob age 30");
    reply = (redisReply*)redisCommand(c, "HGETALL user:1000");
    std::cout << "Hash - user:1000:\n";
    for (size_t i = 0; i < reply->elements; i += 2)
        std::cout << reply->element[i]->str << ": " << reply->element[i + 1]->str << "\n";
    freeReplyObject(reply);

    // Sorted Set
    redisCommand(c, "ZADD leaderboard 100 Alice 200 Bob");
    reply = (redisReply*)redisCommand(c, "ZRANGE leaderboard 0 -1 WITHSCORES");
    std::cout << "Sorted Set - leaderboard:\n";
    for (size_t i = 0; i < reply->elements; i += 2)
        std::cout << reply->element[i]->str << " : " << reply->element[i + 1]->str << "\n";
    freeReplyObject(reply);

    // Bitmap
    redisCommand(c, "SETBIT user_flags 7 1");
    reply = (redisReply*)redisCommand(c, "GETBIT user_flags 7");
    std::cout << "Bitmap - bit 7: " << reply->integer << "\n"; freeReplyObject(reply);

    // HyperLogLog
    redisCommand(c, "PFADD visitors user1 user2");
    reply = (redisReply*)redisCommand(c, "PFCOUNT visitors");
    std::cout << "HyperLogLog - approximate visitors: " << reply->integer << "\n"; freeReplyObject(reply);

    // Stream
    redisCommand(c, "XADD mystream * user alice action login");
    reply = (redisReply*)redisCommand(c, "XRANGE mystream - +");
    std::cout << "Stream - mystream:\n";
    for (size_t i = 0; i < reply->elements; ++i) {
        redisReply* item = reply->element[i];
        std::cout << item->element[0]->str << " => ";
        redisReply* fields = item->element[1];
        for (size_t j = 0; j < fields->elements; j += 2)
            std::cout << fields->element[j]->str << ": " << fields->element[j + 1]->str << " ";
        std::cout << "\n";
    }
    freeReplyObject(reply);

    redisFree(c);
    return 0;
}

Output Example

String - name: Alice
List - tasks:
- task1
- task2
Set - tags:
- cpp
- python
- redis
Hash - user:1000:
name: Bob
age: 30
Sorted Set - leaderboard:
Alice : 100
Bob : 200
Bitmap - bit 7: 1
HyperLogLog - approximate visitors: 2
Stream - mystream:
1686162828651-0 => user: alice action: login 

Redis in Enterprise: Core Concepts

Redis is often used in enterprise environments as a secondary data store due to its speed, simplicity, and versatility. But in enterprise development, there are specific capabilities, patterns, and pitfalls you should understand when integrating Redis effectively.

1. Primary Use Cases in Enterprise

  • Caching layer (database or API responses)
  • Session storage (especially in stateless web applications)
  • Message broker (via Redis Pub/Sub or Streams)
  • Rate limiting (with atomic counters and TTL)
  • Job queues (via libraries like Bull, RQ, Sidekiq)
  • Real-time analytics (e.g. leaderboard counters, heat maps)

Architectural Considerations

2. Persistence Modes

Redis is often used as ephemeral storage, but it can persist data:

  • RDB (Snapshotting): Less durable, but faster for large-scale reloads.
  • AOF (Append Only File): More durable; logs every write operation.
  • Hybrid: Use both for performance + safety.

Enterprise Tip: Tune the persistence to your SLAs. For most caching use cases, persistence can be turned off.

3. High Availability & Scaling

  • Redis Sentinel: For HA and failover monitoring.
  • Redis Cluster: For horizontal scaling (partitioning keys across nodes).
  • Managed Services: AWS ElastiCache, Azure Cache for Redis, GCP Memorystore simplify scaling & maintenance.

4. Security Best Practices

Redis by default is not secure:

  • Run in private VPCs or behind firewalls
  • Require authentication (requirepass)
  • Use TLS encryption
  • Avoid exposing directly to the internet

Consider Redis ACLs (Access Control Lists) to restrict commands per user/role.

Integration Patterns

5. Cache Aside Pattern (Lazy Loading)

The most common caching pattern:

  • Check Redis for key
  • If not found, fetch from primary DB and store in Redis

This pattern prevents cache staleness and avoids overuse.

6. Write-Through and Write-Behind Caching

  • Write-through: Write to Redis and DB at the same time (risk: slower writes)
  • Write-behind (deferred sync): Write to Redis, then flush to DB in batches (risk: data loss on failure)

7. Data Expiration (TTL) and Eviction Policies

Use EXPIRE wisely to avoid unbounded memory usage.

Eviction policies:

  • noeviction (default): errors when full
  • allkeys-lru, volatile-lru: evict least used keys
  • allkeys-random, etc.

In memory-limited environments, choose wisely.

8. Secondary Use Patterns

As a secondary database, Redis can serve:

  • Fast-access read replicas (shadow copies of slow data)
  • Hot-path optimizations (e.g., frequently queried relationships)
  • Event queues or ephemeral state stores (like order status)

But Redis is not a replacement for relational integrity, so avoid:

  • Transactions involving many keys
  • Large or nested data models
  • Complex queries or joins

Tooling & Libraries

Popular Redis tools:

  • CLI: redis-cli
  • GUI clients: RedisInsight, Medis, Redis Commander
  • Libraries: Almost every language has mature Redis clients
  • Monitoring: Use MONITOR, INFO, or Redis Enterprise dashboards

📉 Common Pitfalls in Enterprise Redis Use

  • ❌ Treating Redis as a primary database without understanding persistence tradeoffs
  • ❌ Using keys with unbounded growth (e.g., pushing forever into a list or set)
  • ❌ Allowing hotkeys (single key accessed too often), which cause bottlenecks
  • ❌ Overusing Redis Pub/Sub for critical messaging — no persistence or delivery guarantees
  • ❌ Not monitoring memory usage or planning for eviction behavior

Advanced Use in Enterprises

  • Redis Streams: Persistent log-like data structures for event sourcing
  • Bloom filters / HyperLogLogs: Probabilistic structures for high-volume data
  • Geo indexing: Location-based data queries
  • Lua scripting: Atomic multi-command logic within the server

✅ Final Takeaways

AspectSummary
Best used forFast access, temporary/derived data, messaging, counters
Not suitable forComplex transactions, long-term relational storage
Must haveHA setup (Sentinel/Cluster), monitoring, security hardening
Enterprise grade?Yes — when used as a complement, not a replacement

Related Articles