Skip to main content

Redis

Redis is a high-performance, in-memory data store that DreamFactory uses for caching, session storage, and rate limiting. It provides sub-millisecond response times and supports advanced data structures for complex caching scenarios.


Use Cases

  • API response caching: Store database query results for faster subsequent requests
  • Session storage: Distribute user sessions across multiple DreamFactory instances
  • Rate limiting: Track API request counts with automatic expiry
  • Queue backend: Process background jobs asynchronously
  • Pub/Sub messaging: Real-time event distribution (advanced)

Prerequisites

Redis Server

Install Redis on your server or use a managed service:

Ubuntu/Debian:

sudo apt update
sudo apt install redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server

Managed Services:

  • AWS ElastiCache for Redis
  • Azure Cache for Redis
  • Google Cloud Memorystore
  • Redis Cloud

Verify Installation

redis-cli ping
# Expected response: PONG

Configuring Redis in DreamFactory

System Cache Configuration

Set Redis as the system cache backend in your DreamFactory environment file (.env):

CACHE_DRIVER=redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_secure_password
REDIS_DATABASE=0

Configuration Options

VariableRequiredDefaultDescription
CACHE_DRIVERYesfileSet to redis to enable
REDIS_HOSTYeslocalhostRedis server hostname or IP
REDIS_PORTNo6379Redis server port
REDIS_PASSWORDNo-Redis authentication password
REDIS_DATABASENo0Redis database number (0-15)
REDIS_PREFIXNodreamfactoryKey prefix for namespacing

Session Storage

To store sessions in Redis:

SESSION_DRIVER=redis

Queue Backend

To use Redis for background job queues:

QUEUE_DRIVER=redis

Creating a Redis Cache Service

In addition to system caching, you can create a Redis service for direct cache API access.

Step 1: Navigate to API Generation

Log in to your DreamFactory instance and select API Generation & Connections. Set API Type to Cache.

Step 2: Create New Service

Click the plus button and select Redis.

Step 3: Configure Service Details

FieldDescriptionExample
NameService name (used in API URL)redis
LabelDisplay nameRedis Cache
DescriptionService descriptionApplication cache service

Step 4: Configure Connection

FieldRequiredDefaultDescription
HostNo127.0.0.1Redis server hostname or IP
PortNo6379Redis port number
PasswordNo-Authentication password
Database IndexNo0Redis database number (0-15)
Default TTLNo300Time to live in minutes before cached values expire

Step 5: Save and Test

Save the service and use API Docs to test cache operations.


API Endpoints

MethodEndpointDescription
GET/api/v2/{service}/List all keys (use sparingly)
GET/api/v2/{service}/{key}Get value by key
POST/api/v2/{service}Store one or more key-value pairs
PUT/api/v2/{service}/{key}Update existing key
DELETE/api/v2/{service}/{key}Delete a key
DELETE/api/v2/{service}Flush all keys (dangerous)

API Examples

Store a Value

curl -X POST "https://example.com/api/v2/redis" \
-H "X-DreamFactory-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"resource": [
{
"key": "user:123:profile",
"value": {"name": "John Doe", "email": "john@example.com"},
"ttl": 3600
}
]
}'

Response:

{
"resource": [
{
"key": "user:123:profile",
"success": true
}
]
}

Store Multiple Values

curl -X POST "https://example.com/api/v2/redis" \
-H "X-DreamFactory-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"resource": [
{"key": "setting:theme", "value": "dark", "ttl": 86400},
{"key": "setting:language", "value": "en", "ttl": 86400},
{"key": "setting:timezone", "value": "UTC", "ttl": 86400}
]
}'

Retrieve a Value

curl -X GET "https://example.com/api/v2/redis/user:123:profile" \
-H "X-DreamFactory-API-Key: YOUR_API_KEY"

Response:

{
"key": "user:123:profile",
"value": {
"name": "John Doe",
"email": "john@example.com"
}
}

Delete a Key

curl -X DELETE "https://example.com/api/v2/redis/user:123:profile" \
-H "X-DreamFactory-API-Key: YOUR_API_KEY"

Check if Key Exists

curl -X GET "https://example.com/api/v2/redis/user:123:profile?check_exist=true" \
-H "X-DreamFactory-API-Key: YOUR_API_KEY"

Response:

{
"key": "user:123:profile",
"exists": true
}

TTL (Time-To-Live)

Set expiration times when storing values:

TTL ValueBehavior
Positive integerExpire after N seconds
0No expiration (persist indefinitely)
-1Use default TTL from service config
Data TypeTTL (seconds)Duration
Session data180030 minutes
User profiles3005 minutes
Reference data8640024 hours
Rate limit counters601 minute
Real-time data3030 seconds

Redis Configuration Best Practices

Security

Bind to localhost or private network:

# /etc/redis/redis.conf
bind 127.0.0.1

Require authentication:

requirepass your_strong_password_here

Disable dangerous commands:

rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command DEBUG ""

Memory Management

Set memory limit:

maxmemory 256mb

Configure eviction policy:

maxmemory-policy allkeys-lru
PolicyDescription
noevictionReturn error when memory limit reached
allkeys-lruEvict least recently used keys (recommended)
volatile-lruEvict LRU keys with TTL set
allkeys-randomRandom eviction

Persistence

RDB snapshots (default):

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

AOF for durability:

appendonly yes
appendfsync everysec

High Availability

Redis Sentinel

For automatic failover:

REDIS_SENTINEL_HOST=sentinel1.example.com,sentinel2.example.com
REDIS_SENTINEL_PORT=26379
REDIS_SENTINEL_MASTER=mymaster

Redis Cluster

For horizontal scaling, configure multiple Redis nodes with clustering enabled.


Monitoring

Key Metrics to Watch

MetricDescriptionAlert Threshold
used_memoryCurrent memory usage> 80% of maxmemory
connected_clientsActive connections> 80% of maxclients
keyspace_hitsCache hit count-
keyspace_missesCache miss countHigh miss ratio
evicted_keysKeys removed due to memoryAny eviction

Redis CLI Commands

# Check server status
redis-cli info

# Monitor memory
redis-cli info memory

# Check connected clients
redis-cli client list

# Get hit/miss ratio
redis-cli info stats | grep keyspace

Common Errors

Error CodeMessageCauseSolution
400Bad RequestInvalid key or valueCheck request format
401UnauthorizedMissing API keyAdd API key header
404Not FoundKey does not existHandle cache miss
500Connection refusedRedis server unreachableCheck Redis server status
500NOAUTHAuthentication requiredAdd REDIS_PASSWORD to .env

Troubleshooting Connection Issues

# Test Redis connectivity
redis-cli -h localhost -p 6379 ping

# Test with password
redis-cli -h localhost -p 6379 -a your_password ping

# Check Redis logs
sudo tail -f /var/log/redis/redis-server.log

Performance Tuning

Connection Pooling

Configure persistent connections in Laravel/DreamFactory:

REDIS_CLIENT=phpredis

Pipelining

For bulk operations, the API supports batch requests that are automatically pipelined.

Key Design

  • Use colons : as separators: user:123:profile
  • Keep keys short but descriptive
  • Use consistent naming conventions
  • Avoid spaces and special characters

Next Steps