Efficient Real-Time Comment Updates in Anvil: Alternatives to Polling?

What I’m trying to do:
I’m building a commenting system for posts in my Anvil app. Currently, I’m using a timer to periodically check for new comments, but I’m looking for a more efficient method that doesn’t require frequent server calls.

What I’ve tried:
I’ve implemented a timer-based system that checks for new comments every 2 seconds. While this works, it’s not ideal as it leads to a lot of server calls, especially when there are multiple users. Here’s a simplified version of my current approach:

Code Sample:

class CommentSystem:
    def __init__(self):
        self.timer = Timer(interval=2)
        self.timer.set_event_handler('tick', self.check_for_new_comments)
        self.add_component(self.timer)

    def check_for_new_comments(self, **event_args):
        new_comments = anvil.server.call('get_new_comments', self.last_check_time)
        if new_comments:
            self.call_js('updateComments',new_comments)
            self.last_check_time = datetime.now()

    def start_checking(self):
        self.last_check_time = datetime.now()
        self.timer.interval = 2

    def stop_checking(self):
        self.timer.interval = 0

Is there a more efficient way to implement real-time updates in Anvil, perhaps using a database listener or a push-based system? I’m looking for a method that could trigger updates on the client side based on new data in the database, without requiring frequent polling.

No. There is currently no other way to do this by default. You can do it using Firebase however Unofficial Anvil Firebase Integration v0.1🔥

Otherwise, I don’t think there is any problem with frequent server calls. Mostly everyone here uses it (including myself) and it shouldn’t make things any worse in my opinion.

1 Like

you should just put this in a no_loading_indicator like:

with anvil.server.no_loading_indicator:
    new_comments = anvil.server.call('get_new_comments', self.last_check_time)

…then it will just look like the comments appear in the background and the user does not notice, especially if you combine it with something like: