A Software Engineer and Occasional Writer.

Build Realtime Apps With Redis PubSub

02 September 2017

Last week I worked with Pusher. Pusher is really amazing product to build scalable realtime apps. Also there is slanger and Poxa, Both are open source implementation compatible with Pusher libraries. But today we will use PHP, NodeJs, SocketIO and Redis Pub/Sub To work with realtime messaging.

Redis Server

First make sure that your redis server is running and you can access it whether through localhost ( at port 6379 or public host Server IP. In order to check if Redis is working properly is sending a PING command using redis-cli:

$ redis-cli ping
WebSocket With NodeJs

We will need the following packages to build WebSockets App in NodeJs. Let’s create a package file package.json.

  "name": "RedisPubSub",
  "version": "1.0.0",
  "description": "Redis PubSub, NodeJS, and",
  "main": "index.js",
  "scripts": {},
  "repository": {
    "type": "git",
    "url": "git+"
  "keywords": [
  "author": "",
  "license": "MIT",
  "bugs": {
    "url": ""
  "homepage": "",
  "dependencies": {
    "express": "^4.14.0",
    "redis": "^2.6.3",
    "": "^1.5.1"

Then create our index.js file.

var express = require('express');
var app = express();
var http = require('http').Server(app);
var redis = require('redis');
var client = redis.createClient("redis://");

var io = require('')(http)

app.use('/', express.static('www'));

http.listen(8000, function(){
  console.log('listening on *:8000');

client.on('message', function(chan, msg) {
  io.sockets.emit(chan, msg);


Then let’s install our packages & run the nodejs server.

$ npm install
$ node index.js
Publish & Receive Messages

Let’s Create Two Clients, one for web application frontend and another for application backend (for example it uses PHP).

Frontend Client

Frontend client is completely based on the NodeJs server to talk to the Redis server. and it uses socket.Io to communicate with NodeJs Server.

    <script src=""></script>
    <script type="text/javascript">
      function fetch() {
        var sock = io("http://localhost:8000");
        sock.on('foo', function(msg) {
  <body onload="fetch()">

Backend Client

Backend client will interact directly with redis server, To build our PHP client we will need to install redis package with composer:

$ composer require predis/predis

Then start to use this package within our application like the following:

include_once dirname(__FILE__) . "/vendor/autoload.php";

$redis = new Predis\Client([
    'scheme' => 'tcp',
    'host' => '',
    'port' => 6379

$redis->publish('foo', 'hello, world!');
Need More!

It is just the beginning :D, If you want to build your own realtime messaging solution, Please check the following Docs:

Please click here to check the complete code we written so far.