Search code examples
mongodbmicroservicesbackenddatabase-replication

Data replication for poll-vote application


Newbie at microservices and backend development here: I'm building a real-time poll application to learn more about microservices and different architectures for the backend. Now I have 2 services that relate to my current problem: Voting and Polls.

Polls: Service to create polls and save them with a poll_id

Voting: Service to add or remove votes - requires the poll_id where the vote event took place

My plan: Have a primary database (poll_id (pk),name (str),voters (list of users), votes (hashmap str:int)) for polls and a replica of it in votes. This way I achieve separation of responsibilities (right?) and don't need two MS to rely on one database. I intend to do this with either mongodb's change stream functionality or use a messaging queue to update the replica every time there's a change in the primary.

My question: Is this the right way to go about it - do I even need to separate votes and polls? What is the ideal way to synchronize the databases in this situation.

I'd appreciate any help, thanks!


Solution

  • This sounds like a generally good approach, though I'd caution to not view this as a replica, which it seems you are.

    The poll service (and its persistence) is authoritative for the question of whether a poll exists (and perhaps when it expires, etc.).

    The voting service (and its persistence) is authoritative for the question of how many votes there are in a given poll.

    This means that no database is authoritative for both.

    The voting service receives events about changes (e.g. creation, update of parameters, etc.) from the poll service and updates it's view of those. It might not care about every change from the poll service and it might not even care about every field of the schema in the poll service's database, which argues against database level replication (which tends to be designed on an assumption that it's the same schema: even if they currently are now, there's no guarantee that they will be in the future, as these services are supposed to be able to evolve independently). Change feeds can be useful as a means of getting an event stream (with some perhaps severe limitations compared to consciously publishing events), but the key is to view them from the consumer's perspective as commands like what users are sending: subject to validation and rejection.

    Similarly, if the poll service (e.g. after the poll has closed) needs to know the current vote tally, it can subscribe to events from the voting service.