Implement pub/sub messaging with Redis
✓Works with OpenClaudeYou are a Redis expert implementing publish-subscribe messaging patterns. The user wants to set up Redis Pub/Sub to handle real-time message broadcasting between publishers and subscribers.
What to check first
- Verify Redis server is running with
redis-cli ping(should returnPONG) - Check that you have the
redisnpm package installed withnpm list redis - Confirm Redis version supports PUBSUB commands with
redis-cli INFO server
Steps
- Install the redis client library with
npm install redis - Create a Redis client instance using
createClient()and connect with.connect() - Subscribe to a channel using
.subscribe(channelName, callback)on the subscriber client - Create a separate publisher client instance to avoid blocking the subscriber
- Publish messages using
.publish(channelName, message)on the publisher client - Handle incoming messages in the subscriber callback with the message data
- Implement error handling with
.on('error')for connection issues - Gracefully disconnect clients with
.disconnect()when shutting down
Code
const { createClient } = require('redis');
// ===== SUBSCRIBER =====
async function setupSubscriber() {
const subscriber = createClient({
host: 'localhost',
port: 6379
});
subscriber.on('error', (err) => console.error('Subscriber error:', err));
await subscriber.connect();
// Subscribe to channel with message handler
await subscriber.subscribe('notifications', (message, channel) => {
console.log(`[${channel}] Received: ${message}`);
});
console.log('Subscriber listening on "notifications" channel');
return subscriber;
}
// ===== PUBLISHER =====
async function publishMessage(message) {
const publisher = createClient({
host: 'localhost',
port: 6379
});
publisher.on('error', (err) => console.error('Publisher error:', err));
await publisher.connect();
const numSubscribers = await publisher.publish('notifications', message);
console.log(`Message sent to ${numSubscribers} subscribers`);
await publisher.disconnect();
}
// ===== PATTERN MATCHING =====
async function setupPatternSubscriber() {
const subscriber = createClient({
host: 'localhost',
port: 6379
});
await subscriber.connect();
// Subscribe to channels matching pattern
await subscriber.pSubscribe('user:*:notifications', (message, channel) => {
console.log(`[${channel}] Pattern match: ${message}`);
});
console.log('Pattern subscriber listening to "user:*:notifications"');
return subscriber;
}
// ===== MAIN EXECUTION =====
async function main() {
try {
const subscriber = await setupSubscriber();
const patternSubscriber = await setupPatternSubscriber();
// Simulate
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.