Developers September 8, 2020

How to create a real-time notification system

iqbalcrat

In one of my side projects, I have a requirement to create a realtime notification system where if any of the users like/comment on my post I should get a notification like in IndieHackers. The backend I am using is the python flask framework as I am more comfortable with it.

What are the best ways of creating this? any thoughts or any links with examples are highly appreciated. Thanks in advance.

  1. 2

    There is a way I tested for a small website and it worked great:

    Use ActiveMQ - it has sub/pub topics and configure it for STOMP protocol. Your backend simply connect to ActiveMQ and publish a message. Add a semi-anonymous field for filtering messages for given user. ActiveMQ is able to handle everything else. If you never worked with message queues, you may spend some time to learn more details.

    In the front-end consume messages using https://stomp-js.github.io/stomp-websocket like this (just sample code, not the production one):

    <script type="application/javascript">
        function createMQConnection() {
            const client = Stomp.client("wss://yoursite.com/api/ws/stomp");
            client.debug = function () {
            };
            client.reconnect_delay = 5000;
            client.connect("anonUser", "",
                function () {
                    client.subscribe("/topic/notifications",
                        function (message) {
                        // process message
                        }
                        // JMS selector:
                        , headers = {
                            'selector': "userid = '1000000'"
                        }
                    );
                },
                function () {
                    client.disconnect()
                    setTimeout(createMQConnection, 5000)
                }
            );
        }
        createMQConnection()
    </script>
    

    And now, you have a simple solution for receiving messages from backend on frontend. The rest is on you - to fetch notifications, etc. ;-).

  2. 1

    Go for a hosted service. Honestly, I worked in the realtime space as a developer offering one of these hosted services and it's so much simpler than doing it yourself.

    I personally use Ably for realtime notifications on Portabella, works great.

Recommended Posts