1

I'm trying to implement the client-server architecture in Python, where I have:

  • Server application
  • List of clients, who can subscribe to updates via API (sending POST requests to /subscribe endpoint).

It works fine. On the server side, I have a list of subscriber's URLs.

The main idea is to send requests from the server to all subscribed clients every X seconds (something similar to monitoring system).

I'm trying to do this part using threads:

class Monitor(threading.Thread):
    def __init__(self):
        super(Monitor, self).__init__()
        self.setDaemon(True)

    def send_notifications(self, subscribers):
        for subscriber in subscribers:
            request.post(subscriber["url"], json=subscriber["data"], timeout=0.5)

    def run(self):
        subscribers = get_subscribers()  # getting list of subscribers via API call.
        while True:
            self.send_notifications(subscribers)
            time.sleep(Y)

More or less it works, but I need to improve it a little. The expected behaviour is: The server should send notifications every X seconds to each subscribed client. If sending the notification to some client fails for Y minutes(5 minutes for example) it should unsubscribe this unresponsive client.

Is there some best practices for this?

smart
  • 1,975
  • 5
  • 26
  • 46
  • Are you confident that your server will be able to make outgoing TCP connections to the clients? (in across-the-Internet scenarios, most clients will be firewalled and/or NAT'd, making it difficult or impossible for them to accept an incoming TCP connection from a server) – Jeremy Friesner Jan 03 '18 at 16:20
  • @JeremyFriesner, currently it's not an issue. I just want to add this logic to unsubscribe clients, which were turned off at all. – smart Jan 03 '18 at 16:23
  • Well, timing out unresponsive clients is a pretty common thing to do; I can't think of any reason not to do it. The only potential "gotcha" would be accidentally timing out a client that was still alive, but had an intermittent network connection; in that case you'd probably want to augment the client with some mechanism for realizing when it had been unilaterally unsubscribed and resubscribing again once its network connectivity had been restored. – Jeremy Friesner Jan 03 '18 at 16:25
  • If you are using the `requests` package (which it looks like you are), I'd recommend looking at this answer: https://stackoverflow.com/a/35504626/955340 and this documentation: http://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html for implementing exponential backoff (retrying less and less frequently till you either manage, or the timeout is reached). –  Jan 03 '18 at 16:38

0 Answers0