Is adding ETag to strongly typed model really a bad idea?

Viewed 876

I am implementing an optimistic concurrency with DocumentDb API using .NET SDK.

On several places i have found mentioning that having ETag on strongly typed model is a bad idea. Explicitly here: https://www.google.hr/amp/s/peter.intheazuresky.com/2016/04/28/documentdb-revisited-part-3-concurrency-in-documentdb/amp/

Even official examples on github show it using dynamic/Document classes instead of strongly typed ones.

Now, what i dont understand is why not storing ETag on model? According to docs, ETag, just like other resource properties (exception is id) is get only and is always changed exclusively by the server. Ref: https://docs.microsoft.com/en-us/azure/cosmos-db/documentdb-resources#system-vs-user-defined-resources

So, if we put ETag on our model and:

  1. read document from db to strongly typed model with etag property

  2. send it to client (lets ignore for simplicity presentation layer dtos)

  3. client updates it and send back

  4. we send update/replace to cosmosdb (with AccessCondition set to etag gotten from client and still in one of the models properties)

I have a hard time finding a problem there? Why bothering with dynamics/Document at all?

Or am i missing something obvious?

3 Answers

Etag is server construct, and initially your document is born without it. IMHO it is a matter of how purist you want to be about your document.

As the example says you can have the ETag and have your pure object (theOrder) too

var theOrder = (Order)(dynamic)orderDoc;

Debug.WriteLine(theOrder.Customer.FirstName + “. Etag “ + orderDoc.ETag);

As per the above example you have to keep the returned document object around to get the ETag or should you have a theOrder object go around with Etag property which no one cares and understand till you come to concurrency.

My understanding is that it is bad to include the ETag on the model itself because strong ETags are supposed to be generated from the document bytes.

If the ETag is part of the document, that's never a possibility:

You generate the ETag from the document bytes (a hash function for example). That gives you an ETag string. The moment you set that string on the document's ETag property, the hash doesn't match anymore, so the ETag value is wrong.

You can implement something that will ignore the ETag value in the hash function, but that will be considered a "weak" ETag.

Related