<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Thoughts on coding ...</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/fkaduk/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/fkaduk/feed.xml</link>
    <description />
    <lastBuildDate>Fri, 26 Apr 2019 16:42:09 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Moving to another blog engine...</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/moving-to-another-blog-engine</link>
      <pubDate>Fri, 26 Apr 2019 16:42:08 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=825</guid>
      <description><![CDATA[I'll continue my new posts here: https://fknet.wordpress.com/]]></description>
      <content:encoded><![CDATA[I'll continue my new posts here: <a href="https://fknet.wordpress.com/">https://fknet.wordpress.com/</a>]]></content:encoded>
    </item>
    <item>
      <title>How Skype modernized its backend infrastructure using Azure Cosmos DB</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/how-skype-modernized-its-backend-infrastructure-using-azure-cosmos-db</link>
      <pubDate>Fri, 26 Apr 2019 16:40:13 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=815</guid>
      <description><![CDATA[Whole story starts here:...]]></description>
      <content:encoded><![CDATA[Whole story starts here: <a href="https://azure.microsoft.com/en-us/blog/how-skype-modernized-its-backend-infrastructure-using-azure-cosmos-db-part-1/">https://azure.microsoft.com/en-us/blog/how-skype-modernized-its-backend-infrastructure-using-azure-cosmos-db-part-1/</a>

&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>CosmosDB change feed support for manual checkpoint</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/cosmosdb-change-feed-support-for-manual-checkpoint</link>
      <pubDate>Wed, 28 Nov 2018 22:55:16 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=455</guid>
      <description><![CDATA[It was quite long time I wrote last post about the change feed processor. Let's continue the series....]]></description>
      <content:encoded><![CDATA[It was quite long time I wrote last post about the change feed processor. Let's continue the series. This time, let's look into a manual checkpoint feature.
<h2>Basics</h2>
Let's refresh the knowledge. CosmosDB change feed processor SDK is a library for dispatching the document-related changes (inserts, updates) as a stream of documents. The documents can be split into multiple partitions (determined by partition key). The change feed processor is able to read the changes from all partitions and the reading is executed in the batches. In order to move forward with reading the documents, the change feed need to track the last processed batch. The tracking process is in the form of storing the continuation token from the last processed batch - that's done using "checkpoint" method. The checkpoints are kept in the lease documents.
<h2></h2>
<h2>Automatic checkpoint</h2>
By default, the change feed processor checkpoints the processed batches automatically. Updating the lease document takes some time and costs some request units (RUs). In order to fine-tune it, it's possible to set the frequency of this process.

Let's look at the change feed processing logic for one partition in the pseudo steps:
<ol>
 	<li>read the change feed from the last known "continuation token"</li>
 	<li>dispatch the documents for processing by calling <em>IObserver.ProcessChangesAsync</em></li>
 	<li>wait for the observer to process whole batch</li>
 	<li>if it's time to checkpoint (based on the configured checkpoint frequency), update the lease document with the continuation token from the last processed batch of documents. That's so called "checkpoint" step.</li>
 	<li>repeat from step 1</li>
</ol>
&nbsp;

The whole process is shown on the following picture:

<a href="https://msdnshared.blob.core.windows.net/media/2018/11/automatic_checkpoint.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/11/automatic_checkpoint-1024x465.png" alt="" class="alignnone size-large wp-image-755" width="1024" height="465" /></a>

In most cases, the above algorithm works without issues. But do you see a possible problem?

&nbsp;
<h2>Stuck partition problem</h2>
It's the step 3. The automatic checkpoint algorithm waits until whole batch is processed and then checkpoints. While this waiting no other documents are read and hence processed. It could happen that, e.g. in the batch with 10 documents, there is one document whose processing takes several minutes. In such case, whole change feed partition processing is "paused" and you can't do anything about it. Such situation can be easily detected when change feed estimator is used (for more information see <a href="https://blogs.msdn.microsoft.com/fkaduk/2018/09/13/cosmosdb-change-feed-processor-2-1-released-monitoring-enhancements/">my previous post</a>). See the following graph showing the remaining work on such stuck partition:

<a href="https://msdnshared.blob.core.windows.net/media/2018/11/max_remaining_work.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/11/max_remaining_work.png" alt="" class="alignnone size-full wp-image-765" width="919" height="389" /></a>

I simulated that the processing of some document takes several hours. This stopped reading from the change feed (the number of polling reads per second dropped to zero). The remaining work started to grow. If there would be a defined SLA agreement stating that the events are scheduled for handling within 2 seconds from the time they were inserted into the collection, then the system would not able to meet it.

&nbsp;
<h2>Solution - manual checkpoint</h2>
The solution is to use the manual checkpoint. It's possible to turn off that the automatic checkpoint process. See the following code:

<a href="https://msdnshared.blob.core.windows.net/media/2018/11/disable_checkpoint.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/11/disable_checkpoint.png" alt="" class="alignnone  wp-image-775" width="610" height="464" /></a>

By doing this, the result lease document is never automatically updated. See the following:

<a href="https://msdnshared.blob.core.windows.net/media/2018/11/no_updates.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/11/no_updates.png" alt="" class="alignnone size-full wp-image-785" width="889" height="471" /></a>

That's not good. After the process restart, the change feed would start back from the beginning. We need to checkpoint manually. That's possible using <em>CheckpointAsync</em> method exposed on the interface <em>IChangeFeedObserverContext</em>. But when? We can not wait for whole batch to be processed and then call <em>CheckpointAsync</em>. The simple solution could be like this:
<ol>
 	<li>read the change feed from the last known "continuation token"</li>
 	<li>dispatch the documents for processing by calling<em> IObserver.ProcessChangesAsync</em></li>
 	<li>schedule processing all documents, this will create as many Tasks as we have documents,</li>
 	<li>register scheduled Tasks and <em>IChangeFeedObserverContext</em> instance into manual periodic checkpointer</li>
 	<li>repeat from step 1</li>
</ol>
See the sample code of the observer:

<script src="https://gist.github.com/kadukf/cd7a3942636e2da574f7f0d9f0476c22.js"></script>

The code above is for demonstrating purposes. It integrates the periodic partition checkpointer into the observer. The checkpointer is started when the observer is opened and stops when the observer is closed. In between, when the batches are dispatched for processing, the processing tasks are scheduled and the whole batch is enqueued into the checkpointer. The periodically checks for the last processed batch in the queue. For the running example <a href="https://github.com/kadukf/blog.msdn/tree/master/CosmosDB/ChangeFeed/Sample5/DocumentDB.ChangeFeedProcessor.ConsoleApp">check the sample here</a>.

After running the sample, the result is:

<a href="https://msdnshared.blob.core.windows.net/media/2018/11/lease_document_updated.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/11/lease_document_updated.png" alt="" class="alignnone  wp-image-795" width="647" height="339" /></a>
<h2></h2>
And the console would look like:

<a href="https://msdnshared.blob.core.windows.net/media/2018/11/result.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/11/result.png" alt="" class="alignnone  wp-image-805" width="562" height="350" /></a>

&nbsp;
<h2>Prons and cons of the solutions</h2>
The above solution solves the issue with stuck partition, that's great (advantage). The change feed processor is reading the changes while the previously read documents are still being processed. But if the reading documents and scheduling the work is much faster than its actual processing then it's possible that the instance will be overloaded (disadvantage). It's necessary to limit the number of concurrent document processings, e.g. using Semaphore.

&nbsp;

&nbsp;

That's all for now. In the future posts I'll describe the pitfalls of the change feed processing in general.]]></content:encoded>
    </item>
    <item>
      <title>CosmosDB change feed processor 2.1 released (monitoring enhancements)</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/cosmosdb-change-feed-processor-2-1-released-monitoring-enhancements</link>
      <pubDate>Thu, 13 Sep 2018 21:55:58 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=715</guid>
      <description><![CDATA[There is new version of CosmosDB Change feed processor library released, version 2.1 and two main...]]></description>
      <content:encoded><![CDATA[There is new version of CosmosDB Change feed processor library released, version 2.1 and two main enhancements are:
<ol>
 	<li>Upgrade to <a href="https://www.nuget.org/packages/Microsoft.Azure.DocumentDB/">Microsoft.Azure.DocumentDB</a> 2.0 nuget package</li>
 	<li>Extensions to the monitoring</li>
</ol>
&nbsp;
<h2>Microsoft.Azure.DocumentDB upgrade</h2>
The change feed library was built against latest SDK 2.0. Short! New SDK version brings several improvements and one of the most important change was the new multiplexing connection model. More about it in future blog post.

&nbsp;
<h2>Extensions to the monitoring</h2>
When you take change feed processing seriously, I mean, production ready, you need to be sure that the processing of the feed is working as expected. You need to be sure that "the feed is flowing" which means the feed is in progress and as soon as there is a document change (insert, replace), the change feed processor receives it.

&nbsp;

I wrote about the monitoring in <a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/17/cosmosdb-change-feed-monitoring/">my previous post</a>. The whole monitoring is built on so called "<em>remaining work estimator</em>" which estimates the number of the documents till the end of the feed. There was an improvement introduced into the library.

It's possible to get the estimation per partition now! Why does it matter? Because it give you better visibility into the system. You are able to see what partition is left behind and how far.

Let's see how to create the remaining work estimator instance:

<script src="https://gist.github.com/kadukf/81985c69171f475fea143fe4b3a4de4e.js"></script>

And let's see how to use it:

<script src="https://gist.github.com/kadukf/3eb2b0ac14606b8cb06c02ab1adf4af4.js"></script>

&nbsp;

And that's the result:

<a href="https://msdnshared.blob.core.windows.net/media/2018/09/remaining_work_partitions_result.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/09/remaining_work_partitions_result.png" alt="" class="alignnone size-full wp-image-745" width="984" height="483" /></a>

&nbsp;

&nbsp;
<h2>Real life scenario</h2>
I'm working on the event sourcing system powered by CosmosDB (I'll be writing about it in the future posts) and we are heavily dependent on the change feed. We need to be sure the system works 24/7. We need to be prepared for failures also when using change feed. In this case when a partition processing is stuck.  So, we are monitoring change feed on several levels.

&nbsp;

&nbsp;
<h3>Who process what</h3>
We monitor what process consumes what partition. In other words, we are able to say what process is consuming what partitions. In practice, we record the following metric: data center, role, instance id, database account, partitions.

&nbsp;
<h3>What's the estimated work left to process</h3>
We have a runner which runs periodically and reports what is the estimated work left per account/partition. That's the input for the graphs and alerting. It is built on top of the estimator shown in this post. If any estimated work hits a limit, it means we have a problem with "stuck" partition.

&nbsp;

See the graph of the simulation from our test environment:

<a href="https://msdnshared.blob.core.windows.net/media/2018/09/simulation.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/09/simulation.png" alt="" class="alignnone size-full wp-image-725" width="818" height="427" /></a>

&nbsp;

The red dotted line is an alert level. Once we are alerted, we are able to see what partitions are stuck. Because we record who process what, we are able to find out the instance which was processing the partition last time and diagnose the issue.

&nbsp;

That's all for now, happy monitoring!

&nbsp;

&nbsp;

Previous posts:
<ol>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/07/04/new-cosmosdb-change-feed-processor-released/">New Azure CosmosDB change feed processor released!</a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a></li>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/">Logging in CosmosDB change feed processor</a></li>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/17/cosmosdb-change-feed-monitoring/">CosmosDB change feed monitoring</a></li>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/09/06/cosmosdb-change-feed-processor-leases-and-work-balancing-strategy/">CosmosDB change feed processor – leases and work balancing strategy</a></li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>CosmosDB change feed processor - leases and work balancing strategy</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/cosmosdb-change-feed-processor-leases-and-work-balancing-strategy</link>
      <pubDate>Thu, 06 Sep 2018 19:51:16 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=425</guid>
      <description><![CDATA[The work distribution is the one of the core change feed processor features. The purpose of the...]]></description>
      <content:encoded><![CDATA[The work distribution is the one of the core change feed processor features. The purpose of the change feed processor is to receive and dispatch all the documents from all partitions of the feed collection for further processing. In case of the high load, it's necessary to scale-out the number of processors, so that the documents are processed within desired time SLA.

As you can see, the change feed processing system has to deal with it. The system has to distribute the work between instances somehow.  That's the aim of the so called "partitions balancing strategy". The change feed processor library contains a default implementation of this strategy "EqualPartitionsBalancingStrategy".

&nbsp;

&nbsp;
<h2>EqualPartitionsBalancingStrategy</h2>
This strategy tries to distribute the work evenly between all active hosts. The algorithm is based on the lease documents.

Just a recap. (Taken from <a href="https://blogs.msdn.microsoft.com/fkaduk/2018/07/04/new-cosmosdb-change-feed-processor-released/">my first post</a> in this serie)There are two collections in the game:
<ul>
 	<li><em>Data collection</em> - it's known also as a feed collection. It's a collection of the data over which change feed is processed. It could be created as a partitioned collection so that data are split into separated physical locations.</li>
 	<li><em>Lease collection</em> - it's a collection where the change feed keeps the pointer of last processed document per partition.</li>
</ul>
&nbsp;

Let's see an example of such lease document:
<pre id="preContent">{
  "id": "account.documents.azure.com_EH9XAA==_EH9XAP7EOwA=..2",
  "PartitionId": "2",
  "Owner": "unique_owner_id",
  "ContinuationToken": "\"2468759\"",
  "properties": {},
  "timestamp": "2018-08-01T20:43:54.9476294Z"
}


</pre>
There will be as many lease documents created as there are partitions in the feed collection.
<h3>Id</h3>
Each lease document has "id" which is in the following form:

{prefix}{feed database account}_{feed database resource id}_{collection resource id}..{partition range ID}

The prefix is used to differentiate the change feed processor groups if they use same lease collection. The rest of the parameters in the "id" is self-explanatory.

&nbsp;
<h3>Owner</h3>
That's a string which is uniquely identifying the processor instance. Make sure this string is unique per each processor instance. Otherwise the same documents will be processed as many time as you have the processor instances. We used to name it the following way: {deployment id}_{processor name}_{instance id}

&nbsp;
<h3>Continuation token</h3>
That's the pointer of the last successfully processed document change on the feed.

&nbsp;
<h3>Timestamp</h3>
That's the epoch timestamp of the last change feed checkpoint time or heartbeat time. This timestamp is used by the work balancing strategy to determine whether the lease is expired or not.

If the lease is expired, then it's available to be taken over by any change feed processor instance.

If the lease is not expired, it means that the instance is active and the feed is processed.

The aim of the strategy is to distribute the work evenly between all active instances.

&nbsp;
<h3>Properties</h3>
That's the free form dictionary of string to string. The properties are the form how the strategy executions communicate between each other. It give you a possibility to create more advanced strategies, e.g. when shifting the load between "A/B"  deployments.

The properties can be manipulated by the strategy execution and then they will be persisted.

&nbsp;
<h2>Configuration - Lease expiration interval</h2>
The strategy is configured by the ChangeFeedProcessorOptions.LeaseExpirationInterval. It's the interval for which the lease is taken by the particular owner. It's an interval determining how often the strategy is executed.

So, if the lease is not renewed or checkpoint-ed within this interval, it will be identified as expired and ownership of the partition will move to another change feed processor instance.

If the processor is stopped, the lease is freed-up. It means that the partition won't be processed until some processor instance takes it (which depends on lease expiration interval).

There are special situations when you need to enhance the default work balancing strategy. Imagine you stop the instance. The partitions processed by the stopped instance are not processed until some other instance takes it over. This "gap" depends on the expiration interval. So, if you have strongly time-limited SLA, you will be required to write the custom strategy and leveraging the properties. Ping me if you need more information about it.

Bear in mind, this is really rare condition and almost in all cases you will be more than happy with default strategy. We run quite heavy system using change feed processor with default strategy without issues.

&nbsp;
<h2>Conclusion, consequences</h2>
In case the change feed processor instance <em>crashed</em> and then starts within lease expiration time, it will take back all previously owned leases immediately after start.

In case the instance is gracefully <em>stopped</em>, the owner is reset which means the lease is free to be owned by other change feed processor instance.

In case the number of change feed processor instances is <em>scaled-out</em>, the new ideal work balance is calculated based on the new active instances. The new instance(s) will try to take the ownership of partitions by 1 per each execution cycle configured by lease expiration interval.

Keep in mind that the leases are stored in the lease collection. The collection has its own throughput (== money). In case you set low expiration interval, you can end up with the <em>throtlling</em> issues because leases are scanned once per lease expiration interval by each instance. This can cause that the leases are not taken for longer time and their processing will be delayed.

&nbsp;

Previous posts:
<ol>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/07/04/new-cosmosdb-change-feed-processor-released/">New Azure CosmosDB change feed processor released!</a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a></li>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/">Logging in CosmosDB change feed processor</a></li>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/17/cosmosdb-change-feed-monitoring/">CosmosDB change feed monitoring</a></li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>Multiple ways how to limit parallel tasks processing</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/multiple-ways-how-to-limit-parallel-tasks-processing</link>
      <pubDate>Sun, 02 Sep 2018 20:40:02 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=635</guid>
      <description><![CDATA[I decided to write this post because I saw several implementations how to solve the following...]]></description>
      <content:encoded><![CDATA[I decided to write this post because I saw several implementations how to solve the following interesting exercise across several reviews last days.
<h2>Exercise:</h2>
Let's have a list of items. We need to execute an asynchronous task for each of them in concurrently limited way (aka max degree of parallelism) and we need to collect all the results.

&nbsp;
<h2>Solution #1 using TPL Dataflow library</h2>
There is a nuget <em>System.Threading.Tasks.Dataflow</em> used to solve so called <em>data flow</em> asynchronous processing tasks. Using its ActionBlock&lt;TInput&gt; and the property ExecutionDataflowBlockOptions.MaxDegreeOfParallelism it is possible solve the goal.  You can find more information here: <a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-specify-the-degree-of-parallelism-in-a-dataflow-block">https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-specify-the-degree-of-parallelism-in-a-dataflow-block</a> but let's see how it could be solved.

&nbsp;
<h4>Code</h4>
<script src="https://gist.github.com/kadukf/4ca48b9ee462a48b2b81ad728f8b6d73.js"></script>

&nbsp;
<h4>Result</h4>
<a href="https://msdnshared.blob.core.windows.net/media/2018/08/1.result.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/1.result.png" alt="" class="alignnone size-full wp-image-645" width="980" height="114" /></a>
<h2></h2>
&nbsp;
<h2>Solution #2 using SemaphoreSlim</h2>
Another solution could be to limit the number of concurrent processing by a semaphore, it's kind of rate throttling.

&nbsp;
<h4>Code</h4>
<script src="https://gist.github.com/kadukf/ddc7bd972bdbb0752b1743ee9291bf66.js"></script>

&nbsp;
<h4>Result</h4>
<a href="https://msdnshared.blob.core.windows.net/media/2018/08/2.result.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/2.result.png" alt="" class="alignnone size-full wp-image-655" width="981" height="150" /></a>

&nbsp;

&nbsp;
<h2>Solution #3 using Enumerable.Range and Concurrent Queue</h2>
There is another solution based on the idea of running as many processing loops as we need degree of parallelism to be. The items are provided in thread safe way, using a ConcurrentQueue.

&nbsp;
<h4>Code</h4>
<script src="https://gist.github.com/kadukf/4ecafae97d1661413b029eae90a71e46.js"></script>

&nbsp;
<h4>The result
<a href="https://msdnshared.blob.core.windows.net/media/2018/08/3.result.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/3.result.png" alt="" class="alignnone size-full wp-image-665" width="977" height="122" /></a></h4>
&nbsp;

&nbsp;

&nbsp;
<h2>Solution #4 using Partitioner</h2>
The last solution is by using System.Collections.Concurrent.Partitioner which is aimed to split the input into the buckets (partitions) and process them in parallel.

&nbsp;
<h4>Code</h4>
<script src="https://gist.github.com/kadukf/b1874311ce024c65b4fcd86694b9a1e8.js"></script>

&nbsp;
<h4>Result</h4>
<a href="https://msdnshared.blob.core.windows.net/media/2018/08/4.result.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/4.result.png" alt="" class="alignnone size-full wp-image-675" width="982" height="96" /></a>

&nbsp;

&nbsp;

&nbsp;

That's all for now folks! All samples can be found here: <a href="https://github.com/kadukf/blog.msdn/blob/master/.NET/ParalellizedTasks">https://github.com/kadukf/blog.msdn/blob/master/.NET/ParalellizedTasks</a>

&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>CosmosDB change feed monitoring</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/cosmosdb-change-feed-monitoring</link>
      <pubDate>Fri, 17 Aug 2018 13:15:58 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=445</guid>
      <description><![CDATA[Let's continue in the serie of the posts focused on the CosmosDB change feed. In this post we will...]]></description>
      <content:encoded><![CDATA[Let's continue in the serie of the posts focused on the CosmosDB change feed. <a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/07/04/new-cosmosdb-change-feed-processor-released/"></a>In this post we will focus on the diagnostics.
<h2>Goals</h2>
After running the change feed processor we need to be sure that:
<ul>
 	<li>the documents are processed from all partitions and</li>
 	<li>the age of the documents is within the limit and</li>
 	<li>the costs consumed by change feed processor is under control and</li>
 	<li>the communication between change feed processor and CosmosDB meets QoS requirements.</li>
</ul>
Let's deep dive each aspect from the bottom up.

&nbsp;
<h2>The costs and QoS measurement</h2>
Change feed processor uses DocumentDB SDK to connect and communite with CosmosDB. It connects to two sources: document feed collection and lease collection. Just to recap:
<ul>
 	<li><em>feed collection</em> is the collection providing the documents for processing</li>
 	<li><em>lease collection</em> is a collection used by change feed processor in order to manage and distribute the partitions processing evenly between all change feed processors.</li>
</ul>
Change feed processor gives the developer a possibility to configure how to connect to the collections. By default it creates a DocumentClient under the hood. It also gives a possiblity to pass directly DocumentClient or IChangeFeedDocumentClient instances.

We will use last option here (<em>document client level</em>). Using this approach it will be possible to catch all calls made from change feed processor to document client and meter the calls, frequency, costs and reliability.

&nbsp;

Let's define a metering reporter interface and its console implementation.

<script src="https://gist.github.com/kadukf/6fdc17c532b903a2ea00e9f020936afd.js"></script>

&nbsp;

Let's create a metering decorator for IChangeFeedDocumentClient:

<script src="https://gist.github.com/kadukf/b5e5c167b2ea79d473803ad43d9def5a.js"></script>

&nbsp;

As you can see the change feed query has to be decorated too. Here is the decorator:

<script src="https://gist.github.com/kadukf/7440de7d86dcafa46fc70a3f1f50f95d.js"></script>

&nbsp;

And let's put it all together:

<script src="https://gist.github.com/kadukf/1a3c547e1003496f7690155006cf1c03.js"></script>

That's all. It's possible to run it.

From our experience we used this to see if we have throttling issues when accessing lease collections, when listing the leases, updating the leases, etc. It all adds to the feed processing time so it's worth measuring it.

In addition to the monitoring, using the explicit document client give us a possiblity to fine-tune the  connection policy (e.g. switching to direct TCP connection mode, open connection timeouts, etc).
<h2></h2>
&nbsp;
<h2>Monitoring the age of the documents</h2>
This is the metric which defines how much the change feed processing lags behind. Each document has a field _ts (<em>document level</em>).

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/ts.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/ts.png" alt="" class="alignnone size-full wp-image-615" width="903" height="358" /></a>

&nbsp;

This is a system property representing epoch time (it's the number of seconds! that have elapsed since 00:00:00 (UTC), 1 January 1970) when a document was last updated (e.g. create or replace). That's enough for this measurement. Let's see it in action:

<script src="https://gist.github.com/kadukf/5b5e823a2232da2f02e7cc8217513901.js"></script>

&nbsp;

From our experience this is the one of the metrics we use to define SLA for our service where we measure e2e latency/processing time.  It has one more requirement, time synchronization. So you need to ensure that the servers where the change feed processing is runnning are synchronized with closest <a href="https://www.ntppool.org/en/">NTP servers</a>.

&nbsp;
<h2>Processing the documents from all partitions are moving forward</h2>
This is the most import metric, I think. It's possible to do it on 2 levels:
<ul>
 	<li>observer level</li>
 	<li>document client level</li>
</ul>
&nbsp;

As we saw in the first post from this series, the observer is the component which is getting the feed. Here is the interface:

<script src="https://gist.github.com/kadukf/e9134ac889ce55d09ae59c55a01752fa.js"></script>

&nbsp;

We will leverage OpenAsync/CloseAsync callback methods. The observer is called once the change feed processor instance opens or closes the processing of the partition. This could happen due to reasons like:
<ul>
 	<li>redistributing the partition processing load when scaling up/down the cluster or</li>
 	<li>redistributing the partition processing load when rollout/shutdown the cluster or</li>
 	<li>system error</li>
</ul>
Here is the complete list of the closing reasons:

<script src="https://gist.github.com/kadukf/449adff37e671563cd10e387deb81bab.js"></script>

It's necessary to monitoring high and constant frequency of closing the partitions because it signals an issue, especially reasons Unknown and ObserverError.

Unknow is due to internal change feed processor issues. In such case, inspect the logs (see previous <a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/">post</a>) and report the issue to <a href="https://github.com/Azure/azure-documentdb-changefeedprocessor-dotnet">https://github.com/Azure/azure-documentdb-changefeedprocessor-dotnet</a>.

In case of observer error the issue will be in your code ;)

All other reasons signals transient issues and the system should recover from them.

At the end of the day, you need to monitor that the number of open partitions is equal to the number of all partitions in the collection and there are no closings. This ensures that the processing is working smoothly.

But that's not all, folks. It's also necessary to track that the partitions are being processed. It could happen that the partition processing is open but reading the feed per partition is stuck. Yes, we had such issues in past! So how to solve it?

There is a cheap but "undocummented" way which we will try to get into the library.
<h3></h3>
<h3>Undocummented way</h3>
Reading the partition feed is done by change feed document client and its response has a session token and feed documents. Session token is in the format &lt;partition ID&gt;:&lt;LSN&gt;. LSN is the last commited transaction number per partition.

The document has also "_lsn" which is the LSN which commited the document change (create or   replace).

The whole point is to report that the reading the documents from the particular partitions occurs and that it is progressing till the end. One of the options is to report the remaining work (session LSN - document LSN).

&nbsp;
<h3>Remaining work estimator</h3>
The previous approach was so call "undocummented". There is also other, documented approach built inside change feed processor SDK and exposed via IRemainingWorkEstimator. Let's see it:

<script src="https://gist.github.com/kadukf/37a68a0e9db814886ce4c9b3c0383d97.js"></script>

It has a drawback. The estimator calculates estimated work for whole consumer and collection, not just per partition. So the best option is to go with the undocumented way until it is exposed in SDK. We will fix it!

This helped us to avoid incidents, especially in the early stages of integrating the change feed processor.

&nbsp;

Let's put it all together. As usual, the whole code is at <a href="https://github.com/kadukf/blog.msdn/tree/master/CosmosDB/ChangeFeed/Sample3/DocumentDB.ChangeFeedProcessor.ConsoleApp">my github repo</a>. After running it, the output would be:

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/output.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/output.png" alt="" class="alignnone size-full wp-image-625" width="978" height="503" /></a>

&nbsp;

&nbsp;

&nbsp;

&nbsp;

Previous posts:
<ol>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/07/04/new-cosmosdb-change-feed-processor-released/">New Azure CosmosDB change feed processor released!</a><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/"></a></li>
 	<li><a href="https://blogs.msdn.microsoft.com/fkaduk/2018/08/06/logging-in-documentdb-change-feed-processor/">Logging in CosmosDB change feed processor</a></li>
</ol>
&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>Logging in CosmosDB change feed processor</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/logging-in-documentdb-change-feed-processor</link>
      <pubDate>Mon, 06 Aug 2018 14:41:16 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=585</guid>
      <description><![CDATA[The logging is important part of any library. It's the first thing the developers turn on in case...]]></description>
      <content:encoded><![CDATA[The logging is important part of any library. It's the first thing the developers turn on in case they want to gather runtime information about the library and diagnose the issues. This post focuses on the logging aspect of the change feed processor library.

&nbsp;
<h2>The logging integration</h2>
With new version of the library, there was introduced also new way of logging integration. While in the old 1.x version it was built on top of System.Diagnostics.TraceSource, the new version 2.x uses its own logging integration.

The new logging integration automatically detects the logging framework (Serilog, NLog, log4Net, Enterprise library or Loupe log) used in runtime and uses it by default.

&nbsp;
<h3>Integrating log4net</h3>
Let's see t in the action for using log4net:

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/using_log4net.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/using_log4net.png" alt="" class="alignnone size-full wp-image-555" width="891" height="113" /></a>

with the following configuration inside app.config

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/log4net_appconfig.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/log4net_appconfig.png" alt="" class="alignnone size-full wp-image-565" width="960" height="318" /></a>

The output will be:

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/changefeed_output.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/changefeed_output.png" alt="" class="alignnone size-full wp-image-575" width="960" height="315" /></a>

It's not necessary to do anything more.

&nbsp;
<h2>System.Diagnostics integration</h2>
If your logging system depends on System.Diagnostics.TraceSource, don't worry. The new library version provides its integration. You will need to call the following:

<script src="https://gist.github.com/kadukf/43daf97a6d93da9df039078a579747ab.js"></script>

The logging integration is something that should be reviewed review because it should converge to the same practices as DocumentClient (especially when there is <a href="https://github.com/aspnet/Logging">Microsoft.Extensions.Logging</a>) . The main reasons the logging infrastructure diverges from DocumentClient is:
<ol>
 	<li>the lock contention issues when using System.Diagnostics.TraceSource</li>
 	<li>no support for the nested diagnostics context (NDC)</li>
</ol>
&nbsp;
<h3>The TraceSource lock contention</h3>
In order to avoid the lock contention issue when using System.Diagnostics.TraceSource, you will need to configure your system the following way:

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/tracing_wo_contention.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/tracing_wo_contention-1024x537.png" alt="" class="alignnone size-large wp-image-545" width="1024" height="537" /></a>

This forwards all trace messages from DocumentClient as well as from change feed processor to destination but without causing the lock contention because all trace listeners are marked as thread-safe. Kudos to my colleague Roman for deep diving into this.

&nbsp;

Again, the whole example is published at: <a href="https://github.com/kadukf/blog.msdn/tree/master/CosmosDB/ChangeFeed/Sample2/DocumentDB.ChangeFeedProcessor.ConsoleApp">https://github.com/kadukf/blog.msdn/tree/master/CosmosDB/ChangeFeed/Sample2/DocumentDB.ChangeFeedProcessor.ConsoleApp</a>]]></content:encoded>
    </item>
    <item>
      <title>Benchmarks of the logging with LoggerMessage</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/benchmarks-of-the-logging-with-loggermessage</link>
      <pubDate>Sun, 05 Aug 2018 12:44:45 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=515</guid>
      <description><![CDATA[Recently, I came across the following site: High-performance logging with LoggerMessage in ASP.NET...]]></description>
      <content:encoded><![CDATA[Recently, I came across the following site: <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/loggermessage?view=aspnetcore-2.1">High-performance logging with LoggerMessage in ASP.NET Core</a>.

It says that the logging using LoggerMessage.Define style is a high-performance logging pattern because of:
<ol>
 	<li>boxing of arguments when using extension methods</li>
 	<li>repetitive message template parsing</li>
</ol>
&nbsp;

Fair enough, so I decided to do a benchmark comparing LoggerMessage vs Logger extension method vs. string.Format logging.

I decided to do it because after checking the code:
<ol>
 	<li>boxing of the value types in LoggerMessage.Define style is happening anyway , just later, inside the class LogValues&lt;Tx&gt; (see the method ToArray ).

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/boxing.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/boxing.png" alt="" class="alignnone size-full wp-image-535" width="800" height="527" /></a></li>
 	<li>The same is for the message template parsing (see Microsoft.Extensions.Logging.Internal.LogValuesFormatter.Format method).</li>
</ol>
&nbsp;
<h2>The benchmark sample</h2>
In the sample for the benchmark I setup logging infrastructure without actually writing the messages anywhere. I wanted to measure just the overhead of the different logging style.

<script src="https://gist.github.com/kadukf/9d6f627eb956efd5dafdbbbbadfa7fe2.js"></script>

&nbsp;

The results are:

<a href="https://msdnshared.blob.core.windows.net/media/2018/08/loggermessagebenchmak.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/08/loggermessagebenchmak.png" alt="" class="alignnone size-full wp-image-525" width="794" height="196" /></a>

As you can see, LoggerMessage style of logging is really faster then logging via extension methods but the difference is really small and the code change is quite significant. I saw a discussion that the team wanted to migrate the code base to LoggerMessage style because it's high performant logging. I wouldn't invest in it for already running project.

&nbsp;

At the end of the day, LoggerMessage looks promising, especially if the parsing the message template without boxing would be really implemented. I thought the LoggerMessage.Define parses the message template and generate a custom method on the fly for creating the result message.

&nbsp;

What do you think?]]></content:encoded>
    </item>
    <item>
      <title>New Azure CosmosDB change feed processor released!</title>
      <link>https://docs.microsoft.com/archive/blogs/fkaduk/new-cosmosdb-change-feed-processor-released</link>
      <pubDate>Wed, 04 Jul 2018 10:59:04 GMT</pubDate>
      <dc:creator><![CDATA[Kaduk Frantisek]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/fkaduk/?p=415</guid>
      <description><![CDATA[Introduction
Microsoft Azure CosmosDB is an umbrella over different database services. One of them...]]></description>
      <content:encoded><![CDATA[<h2>Introduction</h2>
Microsoft Azure CosmosDB is an umbrella over different database services. One of them is the schema free database service called DocumentDB. You can read about it <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-introduction">here</a>, it has many great features and components. One of them is "<a href="https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed">change feed</a>" which represents the feed of changed documents (upserts, replace) . The client component exposing this feed is called change feed processor.

&nbsp;

Change feed processor works by querying DocumentDB collection for changes. Then, it outputs the list of documents to the registered observer in the order in which they were modified. The observer can process the changes. After observer processed last document from the batch, the change feed processor could checkpoint (persists) the pointer of last document from the batch into the lease document (optional). The whole process then repeats.  That's all folks!

&nbsp;

We use change feed quite heavily. It our core component. We built an event sourcing system with capture state pattern but I'll write about it in future posts.

Now, let's focus on the change feed processor itself and what's possible with this component.
<h2></h2>
<h2>Package</h2>
Microsoft recently released new version (2.0.4) of <a href="https://www.nuget.org/packages/Microsoft.Azure.DocumentDB.ChangeFeedProcessor/">change feed processor package</a>.  It's client side library built on top of DocumentDB SDK. The source code is located <a href="https://github.com/Azure/azure-documentdb-changefeedprocessor-dotnet">here</a>. I'm one of the contributors to this project.

The newly released package changed the new major package version, 2.x which means there were major changes, refactoring, etc. Upgrading the package from 1.x is seamless but there will be several warning messages generated about obsolete interfaces/classes usage.

New package deprecates old construction logic and introduce new one. That's the main focus of this blog post.

&nbsp;
<h2>High level</h2>
The following picture shows the idea behind the scene.

<a href="https://msdnshared.blob.core.windows.net/media/2018/07/changefeed1.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/07/changefeed1-1024x506.png" alt="" class="alignnone size-large wp-image-485" width="1024" height="506" /></a>

As you can see, there are 3 parts which need to be provided from the developer's perspective:
<ul>
 	<li><em>Data collection</em> - it's known also as a feed collection. It's a collection of the data over which change feed is processed. It could be created as a partitioned collection so that data are split into separated physical locations.</li>
 	<li><em>Lease collection</em> - it's a collection where the change feed keeps the pointer of last processed document per partition.</li>
 	<li><em>Observer</em> - a business logic responsible for processing the documents delivered over change feed.</li>
</ul>
&nbsp;

Creating this whole machinery was changed and provides you different extensibility options. That is the focus of this series of blog posts about change feed.

&nbsp;
<h2>Construction</h2>
It's possible to create change feed processor manually but the preferred way is to use the builder <em>Microsoft.Azure.Documents.ChangeFeedProcessor.ChangeFeedProcessorBuilder</em>. The most simple version is following:

&nbsp;

<script src="https://gist.github.com/kadukf/23ed81e308601181578cdffd44cc17d2.js"></script>

&nbsp;
<h2>Sample</h2>
I created whole sample showing this in the action. Source code is at <a href="https://github.com/kadukf/blog.msdn/tree/master/CosmosDB/ChangeFeed/Sample1/DocumentDB.ChangeFeedProcessor.ConsoleApp">https://github.com/kadukf/blog.msdn/tree/master/CosmosDB/ChangeFeed/Sample1/DocumentDB.ChangeFeedProcessor.ConsoleApp</a>  The sample requires local <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator">Azure CosmosDB emulator</a>  running. The sample console application ensures that the database with feed collection (Input) as well as lease collection (Input.Lease.ConsoleApp) is created.

<a href="https://msdnshared.blob.core.windows.net/media/2018/07/sample1_db.png"><img src="https://msdnshared.blob.core.windows.net/media/2018/07/sample1_db.png" alt="" class="alignnone size-full wp-image-505" width="390" height="267" /></a>

Then it starts the thread which inserts the documents and then it starts the change feed processing machinery with the console logging observer.

<a href="https://msdnshared.blob.core.windows.net/media/2018/07/sample1_db.png"></a><img src="https://msdnshared.blob.core.windows.net/media/2018/07/consoleapp.png" alt="" class="alignnone size-full wp-image-495" width="979" height="512" />

&nbsp;

The console observer logs  when the partition processing is "opened", "closed" as well as when the documents are dispatched for processing.

Because the sample requires at least 2 collections and  Azure CosmosDB emulator supports wheter several single partition collections or  1 multipartition collection, just single partition collection is created in this case, so the processing partition ID is 0.

&nbsp;]]></content:encoded>
    </item>
  </channel>
</rss>