⚠️ This post links to an external website. ⚠️
I recently had the pleasure of implementing a distributed timer in a Phoenix LiveView application. In particular, one user can start a timer, and the other users in their group will see the same timer with roughly the same time. The timer can be paused, restarted, stopped, and have time added to it. This post will outline the timer’s implementation, explaining my thought process with some code snippets along the way. I assume the reader has some understanding of the architecture of a LiveView application.
This post focuses specifically on state management and communication between the client and server. We’ll discuss the use of client-side hooks, server and client-pushed events, and Phoenix Pubsub along with the system design concerns that prompted their use. In the interest of brevity, code snippets elide many details outside of that focus—these snippets are for educational purposes and not production-ready.
In order to deliver a good user experience, the timer has a few requirements:
- Advances smoothly in the user’s browser regardless of network conditions
- May be off from other users’ timers by a few seconds
- Does not rely on the accuracy of the user’s clock
- Retains its state on page refresh or when any or all users disconnect
continue reading on chrisodonnell.dev
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.