Search code examples
node.jsmongodbcrashmongooseproduction-environment

Node.js(&MongoDB) server crashes , Database operations halfway?


I have a node.js app with mongodb backend going to production in a week and i have few doubts on how to handle app crashes and restart .

Say i have a simple route /followUser in which i have 2 database operations

/followUser
----->Update User1 Document.followers = User2
----->Update User2 Document.followers = User1
----->Some other mongodb(via mongoose)operation

What happens if there is a server crash(due to power failure or maybe the remote mongodb server is down ) like this scenario :

----->Update User1 Document.followers = User2
 SERVER CRASHED , FOREVER RESTARTS NODE

What happens to these operations below ? The system is now in inconsistent state and i may have error everytime i ask for User2 followers

----->Update User2 Document.followers = User1
----->Some other mongodb(via mongoose)operation

Also please recommend good logging and restart/monitor modules for apps running in linux.

Right now im using domains for to catch exceptions , doing server.close , but before process.exit() i want to make sure all database transactions are done , can i check this by testing if the event loop is empty or not (how?) and then process.exit(1) ?


Solution

  • You need transactions for this, and since MongoDB doesn't have them here is a workaround http://docs.mongodb.org/manual/tutorial/perform-two-phase-commits/