Conflict resolution
- React Native course
- Advanced
- Lesson 34/83
- 5 min
Learn conflict resolution.
Conflict resolution
A conflict is when the same record is modified both on the device and on the server. For example, while the user is offline they marked a task as 'completed'; the same task was marked 'in progress' on another device. When they come online the two versions conflict.
There are three common strategies for conflict resolution. Server wins: the server's version is always accepted. Device wins: the device's version is accepted. Merge: the fields of both versions are merged. The simplest strategy is 'last write wins'; it decides based on the timestamp. The version with the larger updatedAt field is accepted.
last-write-wins
The last-write-wins strategy compares the updatedAt timestamps of two versions. The newer one (larger timestamp) is accepted; the older one is discarded. This strategy is simple and predictable; but it can overwrite an older change the user made on purpose.
Example: the local task has updatedAt: 1000, the server's has updatedAt: 2000. The server's is newer; so the server's is accepted, the local one is discarded. This decision is written as if (local.updatedAt > server.updatedAt) return local; else return server. On equal timestamps the server is considered the winner; this ensures consistency in distributed systems.
Practice Resolve the conflict
Complete the resolveConflict function. It takes local and server as parameters. Write if (local.updatedAt > server.updatedAt) return local; else return server.
Starter code
export function resolveConflict(local, server) {
// resolve the conflict with last-write-wins
}Sample solution
if (local.updatedAt > server.updatedAt) return local;
return server;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the strategy
const strategy = '____';
const strategy = 'last-write-wins';
Explanation: last-write-wins accepts the latest timestamp.
2 Match each strategy to its purpose
| Term | Meaning |
|---|---|
last-write-wins |
Timestamp |
server wins |
Server version |
device wins |
Device version |
merge |
Merges fields |
3 What does last-write-wins decide based on?
if (local.updatedAt > server.updatedAt) { ... }- Timestamp Correct answer
- Content size
- Version number
- Name length
Explanation: It decides based on the timestamp; the newer one wins.