Database Guide

    Self-Hosted Redis

    Deploy Redis, the lightning-fast in-memory data store, on RamNode VPS. Use as a database, cache, message broker, and streaming engine.

    Ubuntu/Debian
    In-Memory Performance
    ⏱️ 10-15 minutes

    Prerequisites & VPS Selection

    Development

    • • 512MB RAM
    • • Learning & testing

    Small Prod

    • • 1-2GB RAM
    • • Caching, sessions

    Medium Prod

    • • 4-8GB RAM
    • • Larger datasets

    Large Prod

    • • 16GB+ RAM
    • • High-traffic apps

    What You'll Need

    • Ubuntu 22.04/24.04 LTS or Debian 11/12
    • Root or sudo access
    • SSH access configured
    • Basic Linux command line familiarity
    2

    Install Redis

    Install Redis from the official repository for the latest stable version:

    Step 1: Update System Packages
    sudo apt update
    sudo apt upgrade -y
    Step 2: Install Prerequisites
    sudo apt install -y curl gnupg lsb-release
    Step 3: Add Official Redis Repository
    curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
    echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
    Step 4: Install Redis
    sudo apt update
    sudo apt install -y redis
    Step 5: Start and Enable Service
    sudo systemctl start redis-server
    sudo systemctl enable redis-server
    Step 6: Verify Installation
    redis-cli ping

    Success: You should see "PONG" as the response, indicating Redis is running correctly.

    3

    Configuration

    Configure Redis in /etc/redis/redis.conf:

    Open Configuration File
    sudo nano /etc/redis/redis.conf

    Key Configuration Options

    DirectiveDefaultDescription
    bind127.0.0.1IP address(es) to listen on
    port6379TCP port for connections
    daemonizeyesRun as background daemon
    maxmemory0Maximum memory usage limit
    maxmemory-policynoevictionEviction policy when maxmemory reached
    timeout0Client idle timeout (0 = disabled)

    Memory Management

    Set memory limits to prevent Redis from consuming all system RAM:

    Memory Settings
    # Set maximum memory (adjust based on your VPS)
    maxmemory 256mb
    
    # Eviction policy when maxmemory is reached
    # Options: volatile-lru, allkeys-lru, volatile-random,
    #          allkeys-random, volatile-ttl, noeviction
    maxmemory-policy allkeys-lru

    Eviction Policy Comparison

    PolicyDescription
    volatile-lruEvict least recently used keys with expiration set
    allkeys-lruEvict least recently used keys (recommended for caching)
    volatile-ttlEvict keys with shortest TTL first
    noevictionReturn errors when memory limit reached
    4

    Security Hardening

    Secure your Redis installation:

    Password Authentication

    Generate Strong Password
    openssl rand -base64 32
    Set Password in redis.conf
    requirepass YourStrongPassword123!@#
    Authenticate with CLI
    redis-cli
    AUTH YourStrongPassword123!@#

    Network Security

    Bind to Specific Interfaces
    # Only accept local connections (most secure)
    bind 127.0.0.1 ::1
    
    # Accept connections from specific private IP
    bind 127.0.0.1 10.0.0.5
    Configure Firewall (UFW)
    # Allow Redis from specific IP only
    sudo ufw allow from 10.0.0.10 to any port 6379
    
    # Or allow from subnet
    sudo ufw allow from 10.0.0.0/24 to any port 6379
    SSH Tunneling for Remote Access
    # From client machine
    ssh -L 6379:127.0.0.1:6379 user@your-ramnode-vps

    TLS/SSL Encryption (Redis 6.0+)

    Generate TLS Certificates
    sudo mkdir -p /etc/redis/tls
    cd /etc/redis/tls
    
    sudo openssl genrsa -out redis.key 4096
    sudo openssl req -new -key redis.key -out redis.csr -subj "/CN=redis"
    sudo openssl x509 -req -days 365 -in redis.csr -signkey redis.key -out redis.crt
    TLS Configuration in redis.conf
    tls-port 6380
    tls-cert-file /etc/redis/tls/redis.crt
    tls-key-file /etc/redis/tls/redis.key
    tls-auth-clients no

    Disable Dangerous Commands

    Rename/Disable Commands in redis.conf
    # Rename dangerous commands
    rename-command FLUSHDB ""
    rename-command FLUSHALL ""
    rename-command DEBUG ""
    rename-command CONFIG "ADMIN_CONFIG_b4c2d8f1"
    5

    Data Persistence

    Redis offers two persistence mechanisms to protect against data loss:

    RDB Snapshots

    Creates point-in-time snapshots at specified intervals:

    RDB Configuration
    # Save snapshot rules (seconds changes)
    save 900 1        # Save if 1 key changed in 900 seconds
    save 300 10       # Save if 10 keys changed in 300 seconds
    save 60 10000     # Save if 10000 keys changed in 60 seconds
    
    # Snapshot filename and directory
    dbfilename dump.rdb
    dir /var/lib/redis

    Append-Only File (AOF)

    Logs every write operation for better durability:

    AOF Configuration
    appendonly yes
    appendfilename "appendonly.aof"
    
    # Fsync policy options:
    # - always: Most durable, slowest
    # - everysec: Good balance (recommended)
    # - no: Fastest, least durable
    appendfsync everysec

    Hybrid Persistence (Recommended)

    Redis 4.0+ combines RDB and AOF benefits:

    Enable Hybrid Persistence
    aof-use-rdb-preamble yes

    💡 This creates an AOF file that starts with an RDB snapshot followed by AOF commands for optimal recovery.

    6

    Basic Redis Commands

    Connect to Redis
    redis-cli
    # Or with authentication:
    redis-cli -a YourPassword

    Essential Commands

    CommandDescription
    SET key valueStore a string value
    GET keyRetrieve a string value
    DEL keyDelete a key
    EXPIRE key secondsSet expiration time
    TTL keyGet remaining time to live
    KEYS patternFind keys matching pattern
    INFOServer information and statistics
    DBSIZENumber of keys in database
    MONITORReal-time command monitoring

    Working with Data Types

    Strings
    SET user:1:name "John Doe"
    GET user:1:name
    INCR page:views
    Hashes
    HSET user:1 name "John" email "john@example.com"
    HGET user:1 name
    HGETALL user:1
    Lists
    LPUSH queue:tasks "task1"
    RPUSH queue:tasks "task2"
    LPOP queue:tasks
    LRANGE queue:tasks 0 -1
    Sets
    SADD tags:post:1 "redis" "tutorial" "vps"
    SMEMBERS tags:post:1
    SISMEMBER tags:post:1 "redis"
    7

    Common Use Cases

    Session Storage

    Store user sessions with automatic expiration:

    Session Management
    # Store session with 30-minute expiration
    SETEX session:abc123 1800 '{"user_id":1,"role":"admin"}'
    
    # Retrieve session
    GET session:abc123
    
    # Extend session
    EXPIRE session:abc123 1800

    Application Caching

    Cache database queries or API responses:

    Caching Patterns
    # Cache with 5-minute TTL
    SETEX cache:user:1:profile 300 '{"name":"John","email":"john@example.com"}'
    
    # Check if cached
    EXISTS cache:user:1:profile
    
    # Invalidate cache
    DEL cache:user:1:profile

    Rate Limiting

    Implement API rate limiting:

    Rate Limiting
    # Increment request counter (resets every minute)
    INCR ratelimit:api:192.168.1.1
    EXPIRE ratelimit:api:192.168.1.1 60
    
    # Check current count
    GET ratelimit:api:192.168.1.1
    8

    Monitoring & Health Checks

    Health Checks
    # Basic connectivity check
    redis-cli ping
    
    # Detailed server information
    redis-cli INFO
    
    # Memory usage
    redis-cli INFO memory
    
    # Connected clients
    redis-cli INFO clients
    
    # Keyspace statistics
    redis-cli INFO keyspace

    Key Performance Metrics

    MetricWhat to Watch
    used_memoryShould stay below maxmemory setting
    connected_clientsSudden spikes may indicate issues
    blocked_clientsShould typically be 0
    instantaneous_ops_per_secOperations throughput
    hit_rateCache effectiveness (keyspace_hits / total)
    rdb_last_bgsave_statusShould be "ok"
    9

    Backup Strategy

    Automated Backup Script
    #!/bin/bash
    # /opt/scripts/redis-backup.sh
    
    BACKUP_DIR=/var/backups/redis
    DATE=$(date +%Y%m%d_%H%M%S)
    
    # Trigger RDB save
    redis-cli -a "YourPassword" BGSAVE
    
    # Wait for save to complete
    sleep 5
    
    # Copy RDB file
    cp /var/lib/redis/dump.rdb $BACKUP_DIR/dump_$DATE.rdb
    
    # Keep only last 7 days
    find $BACKUP_DIR -name "dump_*.rdb" -mtime +7 -delete
    Schedule with Cron
    # Make executable
    chmod +x /opt/scripts/redis-backup.sh
    
    # Daily backup at 2 AM
    0 2 * * * /opt/scripts/redis-backup.sh
    10

    Troubleshooting

    Common Issues & Solutions

    IssueSolution
    Connection refusedCheck if Redis is running: systemctl status redis-server
    NOAUTH requiredProvide password with -a flag or AUTH command
    OOM (Out of Memory)Increase maxmemory or adjust eviction policy
    High latencyCheck slow commands with SLOWLOG GET 10
    Cannot connect remotelyCheck bind settings and firewall rules
    RDB save failingCheck disk space and permissions on data directory
    View Logs
    # View Redis logs
    sudo tail -f /var/log/redis/redis-server.log
    
    # Check for warnings
    sudo grep -i warn /var/log/redis/redis-server.log
    
    # Check service status
    sudo systemctl status redis-server

    Redis Deployed Successfully!

    Your Redis installation is ready. Redis provides exceptional performance for caching, session management, and real-time data processing.

    Next Steps:

    • ✓ Regularly monitor your instance
    • ✓ Maintain automated backups
    • ✓ Keep Redis updated for security patches
    • ✓ Consider Redis Sentinel for high availability
    • ✓ Explore Redis Cluster for horizontal scaling

    Ready to Deploy Redis?

    Get started with a RamNode VPS and deploy Redis in minutes. Our high-performance infrastructure is perfect for in-memory data workloads.

    View VPS Plans →