Sync supports the standard HTTP If-Match
and ETag
headers for the purpose of conditional mutation. Every response containing a Sync object will return an ETag
value, which currently corresponds 1:1 with revision
in the object body. If you specify this value in some subsequent updates operation, that operation will only succeed if there has been no interleaving update.
In this guide we'll show you how to leverage ETags in REST API requests and also how these are exposed in our JavaScript SDK
Let's walk through an example of updating a document through the REST API to understand how optimistic concurrency works.
1curl -X POST https://sync.twilio.com/v1/Sync/Services/ISxx/Documents \2-d 'UniqueName=MyFirstDocument' \3-d 'Data={firstName:Alice,lastName:Xavier}' \4-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
This will create a document with the following structure:
1{2"account_sid": "ACxx",3"service_sid": "ISxx",4"sid": "ETxx",5"unique_name": "MyFirstDocument",6"revision": "0",7"date_created": "2015-11-24T22:18:57Z",8"date_updated": "2015-11-24T22:18:57Z",9"created_by": "system",10"url": "https://sync.twilio.com/v1/Services/ISxx/Documents/ETxx",11"data": {12"firstName":"Alice",13"lastName":"Xavier"14}15}
Now let's update that object through the REST API.
1curl -X POST https://sync.twilio.com/v1/Sync/Services/ISxx/Documents/MyFirstDocument \2-d 'Data={firstName:Bob,lastName:Xavier}' \3-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
We'll get a response back, and now the revision will be 1.
Similar to our counter example above, let's say there is an argument over whether the first name is Alice, Bob or someone else. Now we have two POST
requests hitting Sync in quick succession:
1curl -X POST https://sync.twilio.com/v1/Sync/Services/ISxx/Documents/MyFirstDocument \2-d 'Data={firstName:Charlie,lastName:Xavier}' \3-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
1curl -X POST https://sync.twilio.com/v1/Sync/Services/ISxx/Documents/MyFirstDocument \2-d 'Data={firstName:Dave,lastName:Xavier}' \3-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
In the above case, it will be the last write wins. Post B will simply overwrite post A. Just like in the mutate example above, what if we want to make sure we are up to date before we make any changes?
The answer is to use the If-Match header mentioned above. First, we make sure we GET
the document revision. Then we pass this revision as a value in the If-Match header when we post our update. This ensures that if we are not the most up to date revision, our update will be rejected.
1curl -X POST https://sync.twilio.com/v1/Sync/Services/ISxx/Documents/MyFirstDocument \2--header 'If-Match':'1a' \3-d 'Data={firstName:Dave,lastName:Xavier}' \4-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
Note the addition of the header If-Match. Now, this operation will fail unless the revision of our document is 1a. The error generated will be:
The revision of the Document does not match the expected revision
Let's take the example of a counter, and we want each separate browser tab to increment the value. The JSON representation is:
{ count:0 }
We will store this in a document called "counter":
1syncClient.document("counter").then(function(doc) {2doc.set({count:1});3});
The above works fine for the first count in the first browser tab, but all that will do is repeatedly set the count to 1 when executed. So let's extend the functionality:
1syncClient.document("counter").then(function(doc) {2if(!doc.value.count) {3doc.set({count:1});4}5else {6var newCount = doc.value.count + 1;7doc.set({count:newCount});8}9});
Now, each time the browser is loaded, the document is opened and the count is increased by 1. If we add a subscription to the document, then browsers which are already open will receive an update to the count themselves:
1syncClient.document("counter").then(function(doc) {2if(!doc.value.count) {3doc.set({count:1});4}5else {6var newCount = doc.value.count + 1;7doc.set({count:newCount});8}910doc.on("updated", function(item) {11console.log("count", item.count);12});13});
So now we have a system where we're counting each browser tab being opened. But now it gets interesting. What if two browser tabs open at the same time, so both of them increment the count at the same time. So let's say there are already 10 open.
Browser tab A opens at the same time as B. So this happens:
1A: 10 + 1 = 11 //I'm the 11th Tab!2B: 10 + 1 = 11 //No... I'm the 11th Tab!
Using doc.set will mean that both browser tabs will attempt to write 11, and both will succeed. So now our count is wrong. So how do we fix this? Let's mutate, people.
1syncClient.document("counter").then(function (doc) {2doc.mutate(function (remoteValue) {3console.log("mutate", remoteValue.count);4if (!remoteValue.count) {5remoteValue.count = 1;6} else {7remoteValue.count += 1;8}9return remoteValue;10}).then(function () {11console.log("mutate_done", doc.value.count);12});1314doc.on("updated", function (item) {15console.log("count", item.count);16});1718});
What's occurring? Using mutate allows us to specify that we want to modify the value only when the local copy of the value is synchronized. So if we use mutate, let's look at our problem again:
1A: 10 + 1 = 11 //I'm the 11th Tab!2B: 10 + 1 = 11 //No... I'm the 11th Tab!
With mutate, B will try to execute, but the server will actually return an error, putting B into conflict. By using the mutate function instead of set, we instruct our client to keep trying the function passed to mutate until it can operate on an in-sync value. This means that even if browser tab C came into the picture at the same time, all three tabs would eventually increment the value correctly.
In the client SDKs (JavaScript, iOS and Android) the above revision management is handled for you and managed through the SDK methods. In the REST API, using If-Match headers enables you to ensure you are operating on the most up to date versions of your data.
Unconditional updates (no If-Match header) will sometimes succeed even when a conditional update (with If-Match) ultimately squashes it. If you need to detect the winner of such a race, you will need to examine the final data. We recommend not racing conditional updates with unconditional ones.