# Cache Instances Overview

DanubeData provides fully managed in-memory cache instances — Redis, Valkey, and Dragonfly — with persistence, replication, and high availability.

## What are Cache Instances?

Cache instances are managed in-memory data stores that provide:

- **High Performance**: In-memory data storage
- **Persistence**: Optional data persistence to disk
- **Replication**: Read replicas for scaling
- **Monitoring**: Real-time performance metrics
- **Security**: Firewall integration and authentication

## Cache Engines

Choose the engine that best fits your workload — all three speak the Redis protocol, so existing Redis clients and libraries work unchanged:

- **Redis** — the industry-standard in-memory store. Versions 7.2, 7.4, 8.0, and 8.4 (8.4 is the default for new instances). Redis 8.0 and later bundle vector sets, native JSON, time series, and bloom-filter data types in the core engine, with I/O threading enabled for higher throughput.
- **Valkey** — an open-source, Redis-compatible fork with no licensing restrictions. Versions 7.2 through 9.1 (9.1 is the default).
- **Dragonfly** — a multi-threaded, Redis-compatible engine that scales with your CPU count for much higher single-instance throughput. Versions 1.23 and 1.24. Priced at a 40–50% premium over Redis/Valkey for the added performance.

## Core Features

### Key Features
- **In-Memory Storage**: Lightning-fast read/write operations
- **Data Structures**: Strings, hashes, lists, sets, sorted sets
- **Pub/Sub**: Message broker functionality
- **Lua Scripting**: Server-side script execution
- **Transactions**: MULTI/EXEC support
- **Persistence**: RDB and AOF options

### Use Cases
- **Session Storage**: Store user sessions
- **Caching**: Cache database queries and API responses
- **Real-time Analytics**: Count and track events
- **Message Queue**: Task queue and pub/sub messaging
- **Leaderboards**: Sorted sets for rankings

## Getting Started

### Create a Cache Instance

1. Navigate to **Cache Instances** in the main menu
2. Click **Create Cache Instance**
3. Enter a name for your instance
4. Choose an engine (Redis, Valkey, or Dragonfly) and version
5. Select a resource profile
6. Configure persistence settings
7. Click **Create Cache**

Your cache instance will be ready in 1-2 minutes!

### Connect to Your Cache

Once your cache is running, you'll receive:
- **Hostname**: Connection endpoint
- **Port**: 6379 on the private network. With public DNS enabled, the public
  hostname listens on its own port instead — see [External Access](#external-access)
- **Password**: Secure password

**Example Connection:**
```bash
redis-cli -h your-cache-hostname -p 6379 -a your-password
```

**Example with Code:**
```python
import redis

r = redis.Redis(
    host='your-cache-hostname',
    port=6379,
    password='your-password'
)

r.set('key', 'value')
print(r.get('key'))
```

### External Access

By default your cache is reachable over your team's private network. To connect from outside the platform, enable **public DNS** on the instance — this opens external access and updates the firewall automatically so clients can connect right away. Turning it back off closes that path just as cleanly.

**The public endpoint uses a different port than the private one.** Public
traffic arrives through a shared load balancer, where your instance gets its own
dedicated port — not 6379. Port 6379 stays correct for private-network
connections. Always copy the port shown next to the endpoint in the dashboard, or
read it from the API:

| Where you connect from | Hostname | Port |
|---|---|---|
| Private network (VPS, other DanubeData resources) | short in-cluster name | `port` (6379) |
| Public internet (public DNS enabled) | public DNS hostname | `dns_port` |

DNS records cannot carry a port number, so resolving the hostname tells you
nothing about which port to use. API clients should read `connection_host` and
`connection_port` — they always resolve to the correct pair:

```bash
curl -H "Authorization: Bearer $DANUBEDATA_TOKEN" \
  https://api.danubedata.ro/api/v1/cache/$CACHE_ID/connection-info
```

```json
{
  "host": "redis-sessions.acme.danubedata.ro",
  "port": 6385,
  "username": "default",
  "password": "...",
  "connection_info": "redis://default:...@redis-sessions.acme.danubedata.ro:6385"
}
```

`GET /api/v1/cache/{id}/credentials` is a compatibility alias that returns the
identical payload; `connection-info` is the canonical route.

Traffic between your cache and your other DanubeData resources over the private network is free — it does not count as billed egress.

## Resource Profiles

Cache profiles are sized by memory. Billing is hourly with a monthly cap; check the dashboard for the live rate.

### Redis / Valkey

| Profile | Memory | Monthly |
|---------|--------|---------|
| Micro | 256 MB | €4.99 |
| Small | 1 GB | €9.99 |
| Medium | 3 GB | €19.99 |
| Large | 6 GB | €39.99 |

### Dragonfly (40–50% premium for multi-threaded performance)

| Profile | Memory | Monthly |
|---------|--------|---------|
| Micro | 256 MB | €6.99 |
| Small | 1 GB | €14.99 |
| Medium | 3 GB | €29.99 |
| Large | 6 GB | €59.99 |

## Persistence Options

### No Persistence
- Fastest performance
- Data lost on restart
- Best for: Temporary caching

### RDB (Redis Database Backup)
- Point-in-time snapshots
- Low performance impact
- Best for: General caching with occasional persistence

### AOF (Append-Only File)
- Every write operation logged
- Maximum durability
- Best for: Session storage, critical data

### RDB + AOF
- Best of both worlds
- Highest durability
- Best for: Production workloads requiring persistence

## Replication

Scale read operations with replicas:

### Add a Replica

1. Go to your cache instance page
2. Click **Add Replica**
3. Select a node
4. Click **Create Replica**

### Benefits
- **Read Scaling**: Offload reads to replicas
- **High Availability**: Automatic failover

## Monitoring

Track cache performance:

### Key Metrics
- **CPU Usage**: Monitor compute resources
- **Memory Usage**: Track memory utilization
- **Connections**: Active client connections
- **Operations per Second**: Command throughput
- **Hit Rate**: Cache hit/miss ratio
- **Network I/O**: Bandwidth usage

### Memory Management
- Monitor memory usage to prevent OOM
- Set eviction policies (LRU, LFU, etc.)
- Configure max memory limit

## Snapshots

Create point-in-time snapshots:

1. Go to your cache instance page
2. Click **Snapshots** tab
3. Click **Create Snapshot**
4. Enter a name
5. Click **Create**

### Automated Snapshots

Running cache instances are also snapshotted automatically on a daily schedule, with configurable retention. Automated snapshots run only while an instance is running, so a stopped cache never accrues wasted backups.

### Use Cases
- Backup before major changes
- Clone cache instances

## Upgrading the Engine Version

Move an instance to a newer Redis, Valkey, or Dragonfly version without recreating it:

1. Open the **Updates** tab on your cache instance
2. Review the versions you can upgrade to and start with one click
3. A snapshot is taken automatically first, so you can restore if anything looks wrong afterward
4. Track progress live on the instance page — the instance shows an **Updating** status while the upgrade runs

## Migrating a Legacy Cache to the Managed Operator

New Redis and Dragonfly caches run on our managed-operator backend by default. If you have an older standalone instance, you can move it across yourself:

1. Open the actions menu on an eligible cache instance and choose **Migrate to managed operator**
2. Available for standalone (non-replicated), running Redis and Dragonfly instances — Valkey support is on the way
3. Track migration progress live, from snapshot through cutover
4. A short downtime window applies during cutover; your password and existing data carry over unchanged
5. Afterwards you get a grace period to confirm everything looks right or roll back — it auto-confirms if you take no action

## Best Practices

### Performance
1. Use connection pooling
2. Batch commands with pipelining
3. Use appropriate data structures
4. Monitor memory usage
5. Set appropriate TTLs

### Security
1. Use strong passwords
2. Enable firewalls
3. Use private networks
4. Disable dangerous commands
5. Regular security updates

### Reliability
1. Enable persistence for important data
2. Use replicas for high availability
3. Take regular snapshots
4. Monitor replication lag
5. Test failover procedures

### Memory Management
1. Set max memory limits
2. Configure eviction policies
3. Monitor memory usage
4. Remove expired keys regularly
5. Use appropriate TTLs

## Common Operations

### Session Storage
```python
# Store session
r.setex(f'session:{user_id}', 3600, session_data)

# Get session
session = r.get(f'session:{user_id}')
```

### Caching
```python
# Check cache first
cached = r.get('api:users:list')
if cached:
    return cached

# Fetch from database
data = fetch_from_database()

# Cache for 5 minutes
r.setex('api:users:list', 300, data)
return data
```

### Leaderboard
```python
# Add score
r.zadd('leaderboard', {user_id: score})

# Get top 10
top_users = r.zrevrange('leaderboard', 0, 9, withscores=True)
```

### Pub/Sub
```python
# Publisher
r.publish('notifications', 'New message')

# Subscriber
pubsub = r.pubsub()
pubsub.subscribe('notifications')
for message in pubsub.listen():
    print(message)
```

## Troubleshooting

### High Memory Usage
1. Check memory stats with `INFO memory`
2. Review eviction policy
3. Set appropriate TTLs
4. Consider upgrading to larger profile

### Slow Performance
1. Check CPU usage
2. Review slow log
3. Use pipelining for multiple commands
4. Add read replicas for read-heavy workloads

### Connection Issues
1. Verify firewall rules
2. Check connection limits
3. Use connection pooling
4. Review network latency

## Next Steps

- [Redis Best Practices](https://docs.danubedata.ro/cache-redis)
- [Redis Replicas](https://docs.danubedata.ro/cache-replicas)
- [Data Persistence](https://docs.danubedata.ro/cache-persistence)
- [Monitoring Guide](https://docs.danubedata.ro/cache-monitoring)

Need help? Contact our support team through the dashboard.

