REST API: Mutation and Conflict Resolution
When dealing with real-time updates, some Twilio API resources utilize the If-Match
and ETag
HTTP headers for the purpose of conditional mutation. Every response containing these objects will return an ETag
value, which you can compare against an If-Match
header.
The following resources currently support this form of conflict resolution:
Let's walk through a workflow using the Task resource:
Create and Update a Resource
We often make requests with the idea of "optimistic concurrency". For example, let's say that you make a request to create a Task, like so:
This will create a Task with the attributes {"foo": "bar"}. Now you can update that object through the REST API.
You'll get a response back, and the attributes will now be {"foo": "bar-SFO"}
. This is optimistic concurrency - you assume that you are the only person making changes to the Task, so foo
used to be bar
, and now it's bar-SFO
.
This might work a lot of the time, but let's say there is an argument over whether the attribute should be bar-SFO
or bar-DEN
. Now you have two POST
requests trying to update the Task in quick succession: POST A (the same request as above) and POST B.
What will happen in this condition?
Resolve Multiple Updates to a Resource
The last write wins. Because we're operating on the model of optimistic concurrency, POST B will simply overwrite POST A.
Fortunately, you can avoid these race conditions. You'll notice that the attributes aren't the only thing that changed when you updated your resource: Your ETag header will have incremented from 0 to 1 in the response.
Now, you can use the If-Match
header to check that the version of the Resource is up-to-date before sending your update through. First, GET
the Task in order to retrieve the ETag
header. Then pass this revision as a value in the If-Match
header when you post your update. This ensures that, if you are not referencing the most up to date revision, the update will be rejected.
Note the addition of the If-Match
header. Now, this operation will fail with a 412
Response because the submitted ETag
value is 0 and the current Attributes are different.
When you're testing or building a simple application, this might not be a critical step. If, however, your resource can be mutated by multiple sources at a time, using these headers will help ensure that you don't accidentally overwrite and/or lose any updates.
Next Steps
- Start making your own requests to the Twilio API
- Secure your app with the Twilio HTTP header, X-TWILIO-SIGNATURE
- Learn more about what to expect in Twilio's HTTP Response
Need some help?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.