#40 Eventual Consistency
FB Likes (Live Updates)
Update the like count on everyone's screen as it changes, without sending every single like to every viewer.
What is being asked
Viewers of a post should see its like count tick upwards live. Design how changes are pushed to clients, and what consistency each viewer can expect.
Requirements
Functional
- Live updates of the count on a post being viewed.
- The viewer's own like appears immediately.
Non-functional
- Millions of posts on screen at once; a few are extremely hot.
- Counts may be seconds behind and need not match between two viewers at the same instant.
- Efficient use of connections and battery.
Design
- A like is recorded and emitted as an event.
- An aggregator batches events per post and, at most once a second or so, writes the new total and publishes "post X is now 12,345".
- Clients subscribe through a realtime gateway to the posts currently on their screen and unsubscribe when they scroll away.
- The gateway forwards the latest total to subscribers. It sends the value, not an increment.
Key decisions and trade-offs
- Eventual consistency is the right model. Each viewer converges to the true number; nobody needs to see every intermediate value.
- Send totals, not deltas. A lost message is then harmless, because the next one corrects it. Deltas would drift.
- Throttle per post. One update a second for a hot post is the same cost whether it received ten likes or ten thousand.
- Read-your-own-writes. The client adds its own like locally at once and reconciles when the next total arrives, so the user never sees their like vanish.
- Push or poll. For posts off screen or apps in the background, do nothing; refresh the count when the post is shown again.
Follow-up questions
- How do you avoid the count on screen going down briefly after a like?
- How would you handle a client that has 200 posts on screen?
- What happens when the gateway loses its subscription state?
- How does this differ from the design for live comments?