Start the Application After Redis Connects

The application must not start accepting connections before Redis is ready when the Redis adapter is required for correct cross-instance broadcasting.

Update src/server.js to connect Redis before starting the HTTP server.

This prevents clients from connecting to an instance that has not completed adapter initialization.

Fail-Fast Startup

If Redis is a required dependency for cross-instance messaging, do not silently start in-memory mode when Redis is unavailable. Either fail startup or implement an explicitly designed degraded mode.

Updated src/server.js
import 'dotenv/config';
import express from 'express';
import { createServer } from 'node:http';
import { initializeSocket } from './config/socket.js';
import { connectRedis } from './config/redis.js';
import { registerChatEvents } from './events/chat.events.js';

const app = express();
app.use(express.json());
app.use(express.static('public'));

const httpServer = createServer(app);

async function startServer() {
  await connectRedis();

  const io = initializeSocket(httpServer);

  registerChatEvents(io);

  const PORT = process.env.PORT || 3000;

  httpServer.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
  });
}

startServer().catch((error) => {
  console.error('Application startup failed:', error);
  process.exit(1);
});

Connects Redis first, initializes Socket.IO with the Redis adapter, registers events, and finally starts the HTTP server.

Key Takeaways
  • Initialize Redis before Socket.IO.

  • Register event handlers before accepting connections.

  • Use fail-fast startup when distributed messaging is required.