Getting Started with SwiftCache in 5 Minutes
Quick start guide to setting up your first Redis cache with SwiftCache. Deploy a managed Redis instance and start caching in minutes.
SwiftCache makes it incredibly easy to add caching to your application. In this guide, we'll go from zero to a working cache in just 5 minutes.
Prerequisites
Before you begin, you'll need:
- A SwiftCache account (sign up here)
- Node.js 18+ or Python 3.8+ installed
- Basic knowledge of your application's database queries
Step 1: Create a Redis Instance
Log into your SwiftCache dashboard and create a new Redis instance:
- Click "Create Instance"
- Choose your region (pick the one closest to your application)
- Select a plan (Free tier is perfect for getting started)
- Click "Deploy"
Your instance will be ready in about 30 seconds. You'll receive:
- Host:
redis-us-east.swiftcache.io - Port:
6379 - Password: Your secure access key
Step 2: Install the Client Library
For Node.js
npm install ioredis
For Python
pip install redis
Step 3: Connect to Your Cache
Node.js Example
import Redis from 'ioredis';
const redis = new Redis({
host: 'redis-us-east.swiftcache.io',
port: 6379,
password: 'your-password-here',
tls: {}, // SwiftCache uses TLS by default
});
// Test the connection
await redis.ping();
console.log('Connected to SwiftCache!');
Python Example
import redis
r = redis.Redis(
host='redis-us-east.swiftcache.io',
port=6379,
password='your-password-here',
ssl=True, # SwiftCache uses TLS by default
decode_responses=True
)
# Test the connection
print(r.ping()) # Should print True
Step 4: Cache Your First Query
Let's cache a database query. Here's a typical pattern:
Before (No Cache)
app.get('/api/users/:id', async (req, res) => {
const user = await db.query(
'SELECT * FROM users WHERE id = $1',
[req.params.id]
);
res.json(user);
});
This query hits the database on every request. Slow and expensive!
After (With Cache)
app.get('/api/users/:id', async (req, res) => {
const cacheKey = `user:${req.params.id}`;
// Try cache first
const cached = await redis.get(cacheKey);
if (cached) {
return res.json(JSON.parse(cached));
}
// Cache miss - fetch from database
const user = await db.query(
'SELECT * FROM users WHERE id = $1',
[req.params.id]
);
// Store in cache for 1 hour
await redis.setex(cacheKey, 3600, JSON.stringify(user));
res.json(user);
});
Now subsequent requests for the same user are served from cache in under 1ms instead of hitting the database!
Step 5: Measure the Impact
Add simple metrics to see your cache working:
let cacheHits = 0;
let cacheMisses = 0;
app.get('/api/users/:id', async (req, res) => {
const cacheKey = `user:${req.params.id}`;
const cached = await redis.get(cacheKey);
if (cached) {
cacheHits++;
console.log(`Cache hit rate: ${(cacheHits / (cacheHits + cacheMisses) * 100).toFixed(1)}%`);
return res.json(JSON.parse(cached));
}
cacheMisses++;
// ... rest of code
});
Common Patterns
Session Storage
// Store session
await redis.setex(
`session:${sessionId}`,
86400, // 24 hours
JSON.stringify(sessionData)
);
// Get session
const session = await redis.get(`session:${sessionId}`);
Rate Limiting
async function rateLimit(userId: string): Promise<boolean> {
const key = `ratelimit:${userId}`;
const count = await redis.incr(key);
if (count === 1) {
// Set expiry on first request
await redis.expire(key, 60); // 1 minute window
}
return count <= 100; // Max 100 requests per minute
}
Leaderboards
// Add score
await redis.zadd('leaderboard', score, userId);
// Get top 10
const top10 = await redis.zrevrange('leaderboard', 0, 9, 'WITHSCORES');
Best Practices
- Use Descriptive Keys:
user:123is better thanu:123 - Set Expiration Times: Always set TTLs to prevent memory bloat
- Handle Cache Failures: Your app should work even if cache is down
- Monitor Hit Rates: Aim for 80%+ cache hit rate
Troubleshooting
Connection Refused
Make sure you're using TLS/SSL. SwiftCache requires secure connections.
Slow Performance
Check that you're connecting from the same region as your cache instance. Cross-region latency adds 50-200ms.
High Memory Usage
Set appropriate TTLs on your keys. Use redis.info('memory') to check usage.
Next Steps
Now that you have caching working, you can:
Questions? Join our Discord community or contact support.
Eric Morris
Part of the SwiftCache engineering team, passionate about distributed systems and performance optimization.