How do you ensure data consistency between two separate databases when performing transactions?
sobes.tech AI
Answer from AI
To ensure data consistency between two separate databases during transactions, several approaches can be used:
-
Two-Phase Commit (2PC) — a classic protocol that guarantees atomicity of transactions across multiple resources. In Node.js, libraries or external transaction managers supporting 2PC can be used.
-
Sagas — a pattern that breaks a long transaction into a series of local transactions with compensating actions in case of errors. This is a more flexible and scalable approach, especially in distributed systems.
-
Using message queues and events — for asynchronous data synchronization between databases, where each operation publishes an event, and the other database reacts to it.
Example using Saga:
// Pseudocode for Saga
async function transferData() {
try {
await db1.insert(data1);
await db2.insert(data2);
} catch (error) {
// compensating actions
await db1.delete(data1);
throw error;
}
}
This approach allows controlling consistency without strict resource locking.