Skip to content

Instantly share code, notes, and snippets.

@robertdempsey
Last active March 11, 2020 09:53
Show Gist options
  • Save robertdempsey/adef3b3581dea3308a17b76fd89f5c55 to your computer and use it in GitHub Desktop.
Save robertdempsey/adef3b3581dea3308a17b76fd89f5c55 to your computer and use it in GitHub Desktop.
Retrieves a document from MongoDB twice, updates it twice, and writes it twice. Points out the danger with doing this in parallel.
// Receive notification of update of property 'b' for system_id: 123
const notification_b = {
system_id: 123,
b: 4
}
// Retrieve state of system_id: 123 from MongoDB
const current_state_before_b_change = {
system_id: 123,
a: 1,
b: 2,
c: 3
}
// Begin to modify state object with new value for 'b' from notification
const state_in_memory_after_b_change = {
system_id: 123,
a: 1,
b: 4,
c: 3
}
// Receive notification of update of property 'a' for system_id: 123
const notification_a = {
system_id: 123,
a: 5
}
// Retrieve state of system_id: 123 from MongoDB
const current_state_before_a_change = {
system_id: 123,
a: 1,
b: 2,
c: 3
}
// Write new object with new value of 'b' to MongoDB
const state_in_mongodb_after_b_change = {
system_id: 123,
a: 1,
b: 4,
c: 3
}
// Begin to modify state object with new value for 'a' from notification
const state_in_memory_after_a_change = {
system_id: 123,
a: 5,
b: 2,
c: 3
}
// Write new object with new value of 'a' to MongoDB
const state_in_mongodb_after_a_and_b_change = {
system_id: 123,
a: 5,
b: 2,
c: 3
}
/**
b's new value has been overwritten because the
'current state' to handle a's change was retrieved
before b's new state was written to MongoDB!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment