<?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>Sharad Cornejo Altuzar's blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/shacorn/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/shacorn/feed.xml</link>
    <description>on performance and avoiding the root of all evil.</description>
    <lastBuildDate>Fri, 21 Oct 2016 00:53:01 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Best practices for using HttpClient on Services</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/best-practices-for-using-httpclient-on-services</link>
      <pubDate>Fri, 21 Oct 2016 00:53:01 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/?p=145</guid>
      <description><![CDATA[Since HttpClient was released back in 2012 it's become the recommended way of talking to the web...]]></description>
      <content:encoded><![CDATA[<p align="LEFT" dir="LTR">Since HttpClient was released back in 2012 it's become the recommended way of talking to the web from C#. It follows the HTTP standard very closely and has very good support for the async programming model. During my years working in Services I've seen it used a lot. Sometimes people hit the same problems.</p>
<p align="LEFT" dir="LTR">Here are some tips on the best way of using it in a service that you expect will be running 24/7.</p>
<p align="LEFT" dir="LTR">- <b>IFF</b> you create a new HttpClient per request you should Dispose it (but <b>don't</b> create a new HttpClient per request).</p>
<p align="LEFT" dir="LTR">The Dispose method is where the HttpClient cleans up the HttpMessageHandler. So if you don’t Dispose it and you keep creating new HttpClients per request you will eventually get out of resources. I recommend the "<b>using</b>" pattern to do this automatically for you.</p>
<p align="LEFT" dir="LTR"><strong>BUT</strong></p>
<p align="LEFT" dir="LTR">- Do <b>NOT</b> recreate HTTPClient for each request. <b>Reuse</b> Httpclient as much as possible</p>
<p align="LEFT" dir="LTR">When you create a new HttpClient to make a request there is a lot of overhead. A new connection will have to be established for each request so you'll have your <a href="https://hpbn.co/building-blocks-of-tcp/#three-way-handshake">Three-way handshake</a> and if you are going through HTTPS the cost will be even <a href="https://hpbn.co/transport-layer-security-tls/#tls-handshake">higher</a>. If you are interested in understanding services performance I recommend a lot that you take a look at "<a href="https://hpbn.co/">High Performance Browser Networking</a>".</p>
<p align="LEFT" dir="LTR">Httpclient was written so that you would keep it alive for as long as your application is alive. The methods on it are threadsafe and it will save you the latency cost of establishing a new connection for each request. And you don't even need to worry about adding locking primitives to it. It just works!</p>
<p align="LEFT" dir="LTR">This is particularly important in services because you might be paying this cost for each customer request. So even though in your tests it doesn’t seem like the impact is a lot, once you deploy you will see this impact. I’ve actually seen profiles that indicate 5-7% CPU usage just spent on tearing down the HttpClients (this is a <strong>lot</strong>!).</p>
<p align="LEFT" dir="LTR">Making it static is fine. This might not always be possible because you might need different properties but you should try to do it for related requests.</p>
<p align="LEFT" dir="LTR">You can also use something like <a href="https://msdn.microsoft.com/en-us/library/6y3d5dts(v=vs.110).aspx">ConnectionGroupName </a> to group multiple requests.</p>
<p align="LEFT" dir="LTR">- Use timeouts to control the behavior of your requests</p>
<p align="LEFT" dir="LTR">Finding out if a connection was established is normally very quick. But if there is a network partition it might take longer. If you are making cross datacenter calls your latency might be even higher. Depending on what your service does, the default value of</p>
<p align="LEFT" dir="LTR"><a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout(v=vs.118).aspx">HttpClient.TimeOut</a> might not be what you want so make sure you add the right value to it.</p>
<p align="LEFT" dir="LTR">- Reuse connections when you can (httpClient.DefaultRequestHeaders.ConnectionClose = false or HttpWebRequest.KeepAlive = true)</p>
<p align="LEFT" dir="LTR">This setting controls if HttpClient will close the connection to the service after <strong>each</strong> request. "Obviously" this is not what you want to do so make sure you have set it to false.</p>
<p align="LEFT" dir="LTR">However some services might actually ask you to close the connection after each request. In particular if your request goes through a load balancer by keeping the connection alive your requests will not go through the load balancer so you might end up getting throttled. I've seen this with some Azure Services. If that is the case see the following recommendation</p>
<p align="LEFT" dir="LTR">- Don't hold those connections forever</p>
<p align="LEFT" dir="LTR">If you set Keepalive to true then those connections will be held forever. If the backend machine is down it might take a long while for your service to realize that is the case (and during this time your service will not be available). Also as mentioned before this does not play very well with LoadBalancers.</p>
<p align="LEFT" dir="LTR">But there is a setting that allows the client to close the active connection after some time has passed and refresh the connection to the backend. This is exactly what we want.</p>
<p align="LEFT" dir="LTR">ServicePointManager.FindServicePoint(new Uri(url)).ConnectionLeaseTimeout = ConnectionLeaseTimeoutMs;</p>
<p align="LEFT" dir="LTR">- Error management</p>
<p align="LEFT" dir="LTR">HttpClient tries very had to not throw. This allows you to examine the Response Status Code and based on that log the result, retry, backoff, etc.</p>
<p align="LEFT" dir="LTR">One exception of this is when there is a TimeOut. In this case The HttpClient will throw a TaskCanceledException so you can catch that and do what you need.</p>
&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>WCF headers as properties</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/wcf-headers-as-properties</link>
      <pubDate>Thu, 14 Jan 2016 17:48:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2016/01/14/wcf-headers-as-properties/</guid>
      <description><![CDATA[&nbsp;
Some years ago my then boss&nbsp;was going on vacation. Before he left he asked me to...]]></description>
      <content:encoded><![CDATA[<p>&nbsp;</p>
<p>Some years ago my then <a title="Sajay" href="https://www.linkedin.com/in/sajayantony">boss</a>&nbsp;was going on vacation. Before he left he asked me to investigate how to improve the performance of a WCF service that was being developed at Microsoft. So I did due diligence and talked with the owners of the system and they mentioned that at some point in the past they had taken profiles and that WCF was spending too much time deserializing headers.&nbsp;</p>
<p>After that I talked with some WCF experts and they mentioned that indeed it could be the case that cracking open the headers to grab/modify a value could take some time. This being a messaging system I figured that was the problem and started working on fixing it.</p>
<p>My solution was (I thought) very clever. This service had a couple of parts. See the attached diagram</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/47/37/3515.logic.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-47-37/3515.logic.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/47/37/3515.logic.png" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-47-37/3515.logic.png" alt="" border="0" /></a></p>
<p>The first part was the Frontdoor which received the message from our customers, added some headers (the message would have headers from our customers so we would just append new ones), modified some others and then forwarded it to a different server</p>
<p>The business logic server would then take that message and use the information in the headers that we added to decide what to do with it (persist it, run some procedure, etc).</p>
<p>And the reason why adding and receiving headers can be expensive in WCF is that they use XML so we need to create a valid XML document and deserialize it to grab the property value. So my solution was to allow the front door to set a property instead of a header. Now typically these are not passed through the wire so my extension would take the message properties and append them to the message buffer. Then the business logic layer would have another piece that removes the property from the message buffer and creates a new property with that value. So there was cost of moving data around but it was measurably faster in my micro-benchmark (6-7% faster if I remember correctly). &nbsp;</p>
<p>The project was very fun, I had to read the <a title="WCF Framing" href="https://msdn.microsoft.com/en-us/library/cc219293.aspx">WCF Framing</a>&nbsp;specification, learn about MultiByteInt31s (unsigned 31 bit integers in a variable length packet), how to create my custom payload so that it would not break WCF and how to insert it efficiently with minimum copying of bytes and with little pressure on the Garbage collector. It took me a couple of weeks of coding and testing it.</p>
<p>&nbsp;</p>
<p>All of this was fine until I went back to the team and asked them for an end to end test to validate my improvements.</p>
<p>And that's when I had to face reality. Even though my micro-benchmark showed a measurable improvement in the end to end test the performance gains were not what I expected. I saw less than 2% improvement and profiles showed that the bulk of the CPU was being spent elsewhere.</p>
<p>This really brought home to me&nbsp;the point of measuring before working on a performance improvement. Of course I learned quite a bit about WCF so I would like to think it was not wasted time :)</p>
<p>So my recommendations when you are trying to fix the performance of a product are: &nbsp;</p>
<ul>
<li>Measure before you start coding.</li>
<li>Do not trust "word of mouth" data&nbsp;</li>
<li>Do not trust micro-benchmarks. it's very easy to game them. Even if you wrote them yourself.</li>
<li>Look at the profile with your own eyes :)</li>
</ul>
<p>So for those interested I have put the code in <a title="github" href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx/So what this proof of concept does is take the special property you want to pass around cheaply and it injects it to the message buffer. And when the message is received it grabs it from the message buffer and puts it as a property. So you don't need to do any XML serialization/deserialization.">github</a>. I've tried to comment the code so that it's obvious what each piece is doing. Here are the interesting files (the ones doing the bulk of the work are the first two):</p>
<ul>
<li><strong>WrappedEncodingBindingElement</strong>&nbsp;-&nbsp;This&nbsp;<strong>bindingElement</strong>&nbsp;class is the one that actually modifies the MessageBuffer on the WritePath and extracts our property from the MessageBuffer on the ReadPath</li>
<li><strong>BinaryFormatHelper</strong> -&nbsp;This is the Helper class that modifies a Buffer to include the desired payload (AppendPayloadAsHeader). It also verifies if a given buffer includes our payload and if it does it extracts it from the buffer (GetAndRemoveHeaderPayload).&nbsp;It uses bufferManager for pooling our buffers (avoid generating garbage) and it also uses Buffer.BlockCopy to copy data efficiently.</li>
<li><strong>OutOfBandPayloadProperty</strong> - Our custom property. Includes the payload and the name so that we can distinguish it from other message properties</li>
<li><strong>WcfHelpers</strong> - Helpers for creating WCF messages, custom bindings and the test service</li>
<li><strong>Program.cs</strong> - includes 3 tests:&nbsp;EncodeDecodeNoWcf,&nbsp;EncodeDecodeWithWcf and&nbsp;EncodeDecodeWithSecureWcf</li>
</ul>
<p>&nbsp;</p>
<p>Again, learn from my mistake. I would only use something like this if you can measurably proof that you are spending too much time serializing/deserializing headers for your real scenarios.</p>]]></content:encoded>
    </item>
    <item>
      <title>Why MongoDB?</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/why-mongodb</link>
      <pubDate>Wed, 13 Jan 2016 23:27:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2016/01/13/why-mongodb/</guid>
      <description><![CDATA[Recently I had to give an internal talk on why our team uses MongoDB as its database.
Relational...]]></description>
      <content:encoded><![CDATA[<p>Recently I had to give an internal talk on why our team uses <strong>MongoDB</strong> as its database.</p>
<p><strong>Relational Databases:</strong> I had experience with SQL Server of course and when I worked in Azure Service Bus I learned how cool SQL Azure can be (or Microsoft Azure SQL Database as it's called now). It&rsquo;s really a relational database in the cloud! I really liked the fact that you could have an application that worked on top of SQL Server and then use pretty much the same application in Azure. As some people know, Service Bus can be installed in your own servers and how you do that is by installing it on top of SQL Server. It was amazing to me that you could use the same profiler and use store procedures in both. It was almost perfect. Of course after working with it for a while I got to experience firsthand the disadvantages that it can have for a large project. At some point I felt as if we were trying to fit a square peg in a round hole. But I still remember how cool it felt that it was even possible. Overall that was a good learning experience.</p>
<p><strong>Key/Value Storage:</strong> Of course when I worked in Azure I also got to work a lot with Azure Table Storage. It&rsquo;s very interesting too: it&rsquo;s really scalable and it forces you to understand how your data is going to be accessed so that you can partition it efficiently. And once you do that you don&rsquo;t have to worry about having too much data. It helps you focus on the data, without having to worry about constraints/schemas/indices/relationships and stored procedures. All you need to worry is the data. Very simple and very powerful. However, to be honest I felt it was too much of a jump from the concept of database I had learned in school. Having to put all the business logic in the application layer felt to me closer to an Excel file than to a Database.</p>
<p>And then I got to work with <strong>MongoDB.</strong>&nbsp;</p>
<p>&nbsp;</p>
<h2>&nbsp;So what is Mongo?</h2>
<ul>
<li>
<p>It&rsquo;s a <a href="https://en.wikipedia.org/wiki/Document-oriented_database">Document</a> database. This means that we don&rsquo;t have the concept of schemas. Your data is persisted in collections of documents.</p>
<p>However unlike Azure Table Storage the documents are nested data. You could have documents inside your documents. Whatever makes sense to your application. So there is no need to flatten your data to match a &ldquo;row&rdquo;. You can think of documents almost as an object in a programming language.</p>
</li>
<li>It&rsquo;s a JSON database and you use Javascript language to talk to it. At first I was skeptical of this but I got used to it very quickly. It also makes it very easy to learn for new developers.</li>
<li>It allows querying the nested data for your document. You can query values in arrays, etc. So the document is not just a blob.</li>
<li>As I said there is no schema: some documents might have fields that other documents don&rsquo;t have. This is very handy when adding new fields. You can have old and new data living in the same database without having to do data migration.</li>
<li>You can add indexes to the nested data! This can make it really fast</li>
<li>It&rsquo;s super versatile. It allows changing the actual DB engine to one that fits your needs (more on this later)</li>
<li>It&rsquo;s really scalable</li>
</ul>
<p>&nbsp;</p>
<h3>Scalability</h3>
<ul>
<li>With a relational Database you typically need to scale <strong>up</strong> if you want to improve performance. That means that you need to add more memory or a better disk or even change to a more powerful machine. This gets expensive very quickly and there is a physical limit on how powerful you can get it.</li>
<li>Instead of this Mongo supports Scaling <strong>out</strong>. That is: you can add extra servers to your existing database servers and use them to increase availability (replication) or performance (sharding).&nbsp;</li>
<li><strong>Sharding</strong> means splitting your collection into pieces. This can help with throughput because different servers will be serving the different pieces.</li>
<li><strong>Replicating </strong>means copying data to other servers. This is done through <strong>Replicasets</strong> in MongoDB and they give us data consistency and partition tolerance. If one or more servers go down we can keep working.</li>
</ul>
<p>&nbsp;</p>
<h3>Engines&hellip;</h3>
<p>MongoDB was designed as a Pluggable Storage Engine. This means that if your application has a particular pattern (writeheavy or readheavy) you can select a different storage engine. This avoids &ldquo;one size fits all&rdquo; that make a DB not good for certain use cases</p>
<ul>
<li><strong>MMAPv1</strong> is a good default engine that has collection level concurrency control. However as of the latest versions of Mongo it has been slowly deprecated for Wiredtiger.</li>
<li><strong>WiredTiger</strong> provides more granular concurrency control. For some benchmarks it shows better performance (up to 10x) than MMAPv1.</li>
<li>Facebook released the <strong>Rocks </strong>storage engine (write-optimized)</li>
<li><strong>TokuMX </strong>is an engine that uses data compression &amp; Fractal Indexing to improve performance (Open Source)</li>
</ul>
<p>&nbsp;</p>
<h3>Profile inside Mongo?</h3>
<p>Unlike other databases the profiler is part of Mongo from the start. You can easily enable it for your application with just one line:</p>
<ul>
<li>db.setProfilingLevel(1)</li>
</ul>
<p>&nbsp;&nbsp; This will take a profile of every operation that takes longer than 100 m</p>
<p>Then you can sort to find the slowest ones like this:</p>
<ul>
<li>db.getCollection('system.profile').find({}).sort({millis:-1})</li>
</ul>
<p>In addition of looking at the profiles you can also look at the logs where the slowest operations are logged by default.</p>
<p>&nbsp;</p>
<h3>MapReduce and Aggregation framework</h3>
<p>Once you have your data it&rsquo;s pretty typical that you want to extract information from it. Instead of having to pull all the data and doing your processing in your application layer MongoDB allows you to take advantage of the server to do some of this.</p>
<p>It has full support of the MapReduce paradigm. This allows you to do grouping operations on your collections such as counting, sums, projections, etc. The best part is that it can be done on your shards so you can do parallel processing of large amounts of data. And this works both for input and output so your results can go to sharded collections as well.</p>
<p>This is good but overkill for most reporting needs. Mongo also has support for in memory aggregation operations. These are really fast and almost as powerful as MapReduce.</p>
<h3>Conclusion</h3>
<ul>
<li>No joins (sometimes this means that you need multiple trips to the DB)</li>
<li>No stored procedures (but you get a powerful Aggregation pipeline and MapReduce support instead)</li>
<li>No transactions (you need to implement two-phase commit yourself)</li>
</ul>
<p>But you get a</p>
<ul>
<li>Document DB</li>
<li>Very powerful Indexes</li>
<li>Familiar Javascript language to query it</li>
<li>Aggregation pipeline and MapReduce support</li>
<li>Replicasets and Sharding</li>
<li>Multiple engines</li>
</ul>
<p>It&rsquo;s fast, it&rsquo;s scalable and it&rsquo;s flexible.&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>Performance notes for MongoDB</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/performance-notes-for-mongodb</link>
      <pubDate>Fri, 08 Jan 2016 19:07:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2016/01/08/performance-notes-for-mongodb/</guid>
      <description><![CDATA[Some performance tips for improving your usage of MongoDB
&nbsp;I spent the past year working with...]]></description>
      <content:encoded><![CDATA[<h4><strong>Some performance tips for improving your usage of MongoDB</strong></h4>
<p>&nbsp;I spent the past year working with MongoDB. Since our service was used for Halo and Call of Duty we had very aggressive scale and performance targets. So as part of our stress runs we identified some scalability issues that had their root cause in our data layer. Luckily MongoDB is a database that has great tools for identifying performance problems. Here are some of the approaches I did for debugging/fixing performance problems in Mongo.</p>
<p>&nbsp;</p>
<h4>Normal operations take too long</h4>
<p><strong>Slow Queries</strong>: This is the most common and the easiest to fix. You need to find out if you have an index that covers the query that is slow. As I mentioned <a href="https://blogs.msdn.com/b/shacorn/archive/2015/11/14/how-do-indexes-work-in-mongodb.aspx">before</a> having indexes will speed up significantly your queries and as a general rule you want to have them for most of your queries. Optimize your queries with indexes!</p>
<p><strong>Slow updates or inserts</strong>: This one is trickier! :) If you follow the previous recommendation you might find that your DB writes are too slow. Here are some operations that can slow down your updates</p>
<ul>
<li>You are grabbing and or modifying large arrays inside your documents.</li>
<li>You are modifying fields that are part of an <a href="https://docs.mongodb.org/manual/core/index-multikey/">array index</a>.</li>
<li>You increase the size of the document you are modifying. This could cause it to move which will cause some IO cost while Mongo is moving stuff around</li>
</ul>
<p>The solution to these might sound like workarounds but they help:</p>
<ul>
<li>Limit the size of the arrays inside your documents</li>
<li>Add padding to the documents when you create them if you know they will grow.</li>
<li>Change your schema to simplify your queries.</li>
</ul>
<p>&nbsp;In our case we found that having indexes would help updates as well (because it would speed up the time it took to find the document to modify). But whenever the rate of updates/finds increased we found our finds would take longer (see below for the reason).</p>
<h4>Normal operations are slow but they should not be slow</h4>
<p>&nbsp;We saw this in our system a lot. Some of the queries would show as optimized in the .explain (See the <a href="https://blogs.msdn.com/b/shacorn/archive/2015/11/14/how-do-indexes-work-in-mongodb.aspx">previous</a> blog for an explanation on what that is) but they would take too long to execute. Or they would show up in our profile as taking longer than 100 ms.</p>
<p>In our case we found that they were blocking waiting on slow operations such as updates.</p>
<p>You can confirm this by using the <strong><a href="https://docs.mongodb.org/manual/reference/command/top/">top command.</a> </strong>This tells you how much time was spent locking for reads or writes. You can also look at the profile for the queries and it will tell you how much time it spent executing vs yielding to other operations.</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;">{<br /> &nbsp; "totals" : {<br /> &nbsp;&nbsp;&nbsp;&nbsp; "records.users" : {<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "<strong>readLock</strong>" : {<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "<strong>time</strong>" : 305264, &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"count" : 2824<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "<strong>writeLock</strong>" : {<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "time" : 13,<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "count" : 1<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br /> }<br /> &nbsp;</p>
</td>
</tr>
</tbody>
</table>
<p>Basically in MongoDB the writer is greedy. What this means is that if there is a write and a read operation the reads will yield to the write. So even if you have a fast query (that takes milliseconds to run normally) it might take very long because it&rsquo;s yielding to slow updates (It's a little more complicated than that. Concurrency behavior changes depending on the engine you use and also if you use sharding or replicasets. See the <a title="FAQ" href="https://docs.mongodb.org/manual/faq/concurrency/">FAQ</a>&nbsp;for the latest update that applies to your configuration).</p>
<p>You have a couple of options:</p>
<ol>
<li>Follow the previous recommendations on speeding up updates</li>
<li>Consider sharding your data so that your reads don&rsquo;t wait on that many writes.</li>
</ol>
<p>&nbsp;</p>
<h4>Slow Aggregates</h4>
<p>Aggregates in Mongo are super powerful! However unlike other queries they will be touching most data in the Database (because you probably are trying to generate aggregate data or some kind of report). So they can easily become the bottleneck of your service. Also as I mentioned in a previous blog post the .explain for it is not great because it will tell you information about the indexes but not about memory.&nbsp;</p>
<ul>
<li>The first and very important tip is to take a backup of your production Database and use that to play around with the aggregates without fear of affecting your production system. Since it&rsquo;s a backup with production data you will be able to measure your improvements. Super useful!</li>
<li>Focus on Memory usage. MongoDB has a Hard limit for the data that is passed in the aggregation pipeline of 100MB. You can turn on Disk usage to go around this but it will really slow down everything. So make sure you are under this limit. (And yes you can save the output of the aggregates to a collection, this can can be great but there is a high perf cost to IO so you still need to reduce the memory usage as much as possible). I found that doing the aggregate in memory is the way to go, so making sure that we were passing the least amount of memory through each stage improved performance quite a bit. Use $Project as early as possible to remove fields you don&rsquo;t use!</li>
<li>Try to avoid tablescans or visiting every document in your collection! Again by filtering out documents that you don't care early in the pipeline you will improve performance. Use $match as soon as possible to make the aggregation pipeline happy!</li>
</ul>
<div>Project and Match before sorting/unwinding:</div>
<ul>
<li>If you are using an operator like $sort, it has to go through all the documents. This can get very expensive if you haven&rsquo;t done project + match before.</li>
<li>Unwind creates new documents which duplicates data&nbsp;</li>
</ul>
<ul>
<li>Index will help both match and sorts. So use indexes as much as possible. Note that this are only useful before you transform stuff (project, group, unwind) so make sure you measure that it helps (otherwise why add an index that is not helping?)</li>
</ul>
<p>&nbsp;</p>
<p>Make sure you MEASURE your fixes through all the pipeline. That is the great thing of using a production backup. You can get an idea of the performance impact of your changes.</p>
<p>&nbsp;</p>
<p>Combining<strong> Sort and limit</strong> will keep around only the amount of documents that you passed to limit. So even though it will need to go through the entire collection the aggregation pipeline is smart enough to discard the documents that it does not need. Good for memory!</p>
<p>Project is supposed to be optimized (as in, the pipeline will try to infer if you don't need a field and move the project to the earliest possible moment). However in my local tests I found that making the change myself was much better.&nbsp;</p>
<p>So try to reduce work for the next stage in the pipeline in each step. And after every optimization make sure you measure!</p>
<p>&nbsp;</p>
<h4>Some other options (that we did not need to do)</h4>
<p>1)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Upgrade your hardware! Make sure your working set fits in RAM. We use pretty beefy machines for our Database so we did not need to worry about this.</p>
<p>2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Use fast disks (SSDs) to speed up writes and reads (try to avoid page faults if you can)</p>
<p>&nbsp;&nbsp;</p>
<p>Good luck!</p>]]></content:encoded>
    </item>
    <item>
      <title>How do indexes work in MongoDB</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/how-do-indexes-work-in-mongodb</link>
      <pubDate>Sat, 14 Nov 2015 17:43:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2015/11/14/how-do-indexes-work-in-mongodb/</guid>
      <description><![CDATA[This year I have been working on Xbox Live Compute (or Thunderhead as we know it internally). This...]]></description>
      <content:encoded><![CDATA[<p>This year I have been working on <a href="https://www.respawn.com/news/lets-talk-about-the-xbox-live-cloud/">Xbox Live Compute</a> (or <a href="https://www.polygon.com/2015/8/11/9132195/crackdown-3-multiplayer-cloud-xbox-one-gamescom-2015">Thunderhead</a> as we know it internally). This is a product that uses MongoDB as its main Database. So I have had to learn how to investigate performance and scalability issues with this document DB.</p>
<p>It&rsquo;s been very fun! Here are some of my learnings related to indexes and how they are different to other DBs. Hoping this will save people some time when they need to work with MongoDb.&nbsp;</p>
<h2>How are Indexes special in MongoDB?</h2>
<p>MongoDB allows you to do different operations to the data you store in it. A very big feature compared to other Document DBs is that it supports secondary indexes on its collections. You can create simple and complex indexes and they will be used for speeding up finds (queries), matches (in aggregates) and sorts. It has support for indexes on multiple fields, on arrays, on geospatial fields and even text indexes to speed up searching for string content.</p>
<p>&nbsp;</p>
<p><strong>There ain't no such thing as a free lunch </strong>though<strong>: </strong></p>
<ul>
<li>Indexes speed up queries significantly but they slow down writes.</li>
<li>Updates are a special case: they might speed up finding your document but if the value on any indexed fields is changed the index needs to be updated. So you might get a similar impact as in inserts.</li>
<li>In my measurements I saw reads could improve up to 1000% but writes slowed down almost 30%. Overall it should be a big gain since we do a lot more reads than inserts.</li>
<li>Something of note is that they not only affect write operations. They might slow down read operations as well (such as aggregations). This is because aggregations yield to writes so if your writes are slower your aggregation will take longer to complete. So make sure you measure your performance interleaving writes+reads (or run in stress).</li>
</ul>
<p>&nbsp;</p>
<p>&nbsp; I think MongoDB&rsquo;s QueryOptimizer does a good job. It can be overriden (.hints and $natural for forcing full collection scans) but I could not find a place where it's needed. It's nice having the option of course.&nbsp;</p>
<h2>How to know if an index is being used?</h2>
<p>&nbsp;In the Mongo shell you can use .explain() for normal queries and runCommand+explain for aggregates. Examples:</p>
<p>1)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; db.myCollection.find({}).explain()</p>
<p>2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;db.runCommand({ aggregate: "myCollection", pipeline: [{"$match":{}}], explain: true })&nbsp;</p>
<h2>Compound indexes</h2>
<p>Compound index is when you have more than one field as part of your index. Like this:</p>
<p><strong>Index</strong>: {ServiceId, LastRecordedState}</p>
<p><strong>Query:</strong> {ServiceId, LastRecordedState} &ndash; Uses the index of course</p>
<p><strong>Query:</strong> {ServiceId} - it WILL also use the index. This is pretty nice. Because of this once you have a compound index you can remove your simpler indexes if the compound index is a superset.</p>
<p><strong>Query:</strong> {LastRecordedState} - index will not be used because there is no ServiceId in the query</p>
<p>&nbsp;</p>
<p><strong>SORTS:</strong></p>
<p>db.collectionName.find().sort({ServiceId: 1,LastRecordedState:1}).explain() uses the index</p>
<p>db.collectionName.find().sort({ServiceId:-1,LastRecordedState:-1}).explain() uses the index</p>
<p>db.collectionName.find().sort({ServiceId: 1,LastRecordedState:-1}).explain() does not use the index</p>
<p>db.collectionName.find().sort({ServiceId:-1,LastRecordedState:1}).explain() does not use the index</p>
<h2>Intersect indexes</h2>
<p>&nbsp;If you have these two indexes:</p>
<p><strong>Index:</strong> {ServiceId}</p>
<p><strong>Index:</strong> {LastRecordedState}</p>
<p>&nbsp;Mongo will try to combine the results of the indexes. You can verify this by looking at the &ldquo;explain&rdquo; for your query and find a stage named: AND_SORTED</p>
<p>&nbsp;</p>
<p><strong>Query:</strong> {ServiceId, LastRecordedState} could try to combine both queries. However, this depends on the Query performance. In my tests the query with the simple Index would be selected always. (Because LastRecordedState would return too much data) &nbsp;</p>
<h2>Names for your indexes</h2>
<p>You can use up 31 fields in a compound index, but the default name will be too long. So you should pass a different name:</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p>var indexOptions = new IndexOptionsBuilder();</p>
<p>indexOptions.SetName("ServiceId_LastRecordedState ");</p>
<p>collection.CreateIndex(keys, indexOptions);</p>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;&nbsp;</p>
<p>Other tips:</p>
<ul>
<li>You can create indexes before the field exists in the collection. Or even before the collection exists</li>
<li>You can query if indexes exist: db.system.indexes.find({ns:"databaseName.collectionName"})</li>
</ul>
<p>&nbsp;</p>
<p>If the query uses information that exists in the index the result could be much faster. Most of the time this won&rsquo;t be the case (you might need to disable some fields using a projection), you can see in the explain if the INDEXONLY value is true or fales.&nbsp;</p>
<h2>&nbsp;How to make sense of the output of Explain:</h2>
<p>&nbsp;</p>
<p>As mentioned before you can use the .Explain option to evaluate if a given query is using indexes or why it&rsquo;s taking so long to execute. Here are some tips on how to make sense of the output of this:</p>
<p>&nbsp;</p>
<p>"queryPlanner" : {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "plannerVersion" : 1,</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "namespace" : "databaseName.collectionName",</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "indexFilterSet" : false,</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "parsedQuery" : {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;"$and" : []</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "winningPlan" : {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "stage" : "COLLSCAN",</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "filter" : {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "$and" : []</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "direction" : "forward"</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "rejectedPlans" : []</p>
<p>&nbsp;&nbsp;&nbsp; },</p>
<p>&nbsp;</p>
<p>"executionStats" : {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "executionSuccess" : true,</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "nReturned" : 12191,</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "executionTimeMillis" : 16,</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "totalKeysExamined" : 12191,</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "totalDocsExamined" : 12191,</p>
<p>&nbsp;</p>
<p>WINNINGPLAN is the plan that Query Analyzer picked because it finished faster. It will cache it and reuse it for future queries (until you add indexes, reindex, make changes to the collection, etc)</p>
<p>&nbsp;</p>
<p><strong>Stages:</strong></p>
<p>COLLSCAN for a full collection scan (did not use your index. You do NOT want this)</p>
<p>IXSCAN for scanning index keys (used the index to find)</p>
<p>FETCH for retrieving documents that it found (most of the time you will see this combined with IXSCAN)</p>
<p>&nbsp;</p>
<p>KEEP_MUTATIONS stage: When documents are deleted or updated some Query stages can receive invalidation notices. Some stages flag documents that are deleted. The set of flagged documents is then read by the KEEP_MUTATIONS stage, which re-checks these documents against the query and returns them if they still match. Note that this is not used for the WiredTiger engine, only for the MMAPv1.</p>
<p>&nbsp;</p>
<p>"AND_SORTED": You will see this when Mongo used a combined index</p>
<p>queryPlanner.winningPlan.inputStage.stage displays IXSCAN to indicate index use.</p>
<p>executionStats.nReturned displays 12191 to indicate that the query matches and returns 12191&nbsp;documents.</p>
<p>executionStats.totalKeysExamined display 12191 to indicate that MongoDB scanned 12191&nbsp;index entries (Note that this is a Full table scan).</p>
<p>executionStats.totalDocsExamined display 12191 to indicate that MongoDB scanned 12191&nbsp;documents.</p>
<p>&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>Azure Event Hub / Service Bus Performance - Http Batch Send 2</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/azure-event-hub-service-bus-performance-http-batch-send-2</link>
      <pubDate>Fri, 16 Jan 2015 14:41:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2015/01/16/azure-event-hub-service-bus-performance-http-batch-send-2/</guid>
      <description><![CDATA[After the previous post on Http Batch send for Service Bus I received some emails with questions. I...]]></description>
      <content:encoded><![CDATA[<p class="MsoNormal">After the previous post on Http Batch send for Service Bus I received some emails with questions. I looked at the <a href="https://msdn.microsoft.com/en-us/library/azure/dn798894.aspx">msdn</a> documentation for both Service Bus and Event Hub and noted they are missing some information. Event Hub <a href="https://msdn.microsoft.com/en-us/library/azure/dn790664.aspx">documentation</a> does not even mention Batch Send. So here is another post about Batch Send.</p>
<p class="MsoNormal">&nbsp;</p>
<h2>Does Event Hub support batch send?</h2>
<p class="MsoNormal">YES!</p>
<p class="MsoNormal"><a href="https://azure.microsoft.com/en-us/services/event-hubs/">Azure Event Hub</a> was developed by Microsoft to support IoT scenarios. It was written by the same team that owns Azure Service Bus (that is why it&rsquo;s under the Service Bus Namespace) so they share a big part of their codebase. As a matter of fact I worked on the Batch Send feature to improve the throughput of the Http code path for Eventhub. But as we were working on it we made sure it was working for Service Bus as well.</p>
<p class="MsoNormal">&nbsp;</p>
<h2>Since I&rsquo;m serializing as JSON do I need to change something in the Receive?</h2>
<p class="MsoNormal">Nothing changes in the receive path. Json is only used to create the batches of messages, but in the receive code path we will be receiving them separately. The batch is gone by then.</p>
<p class="MsoNormal">&nbsp;</p>
<h2>Can you show a few samples on how to send different payloads?</h2>
<p class="MsoNormal">Like I said in my previous post this is the format for an Http Message:</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> public</span><span>&nbsp;<span><span style="color: blue;">class</span><span>&nbsp;<span><span><span style="color: #2b91af;">HttpBrokeredMessage</span><span>&nbsp;<br />{<br />&nbsp; <span style="color: blue;"> public</span><span>&nbsp;<span><span><span style="color: #0000ff;">string</span><span>&nbsp;Body { <span><span style="color: #0000ff;"> get</span><span>; <span><span style="color: #0000ff;"> set</span><span>; }<br />&nbsp;&nbsp;<span><span style="color: #0000ff;">public&nbsp;</span><span>Dictionary&lt;<span><span style="color: #0000ff;">string</span><span>, <span><span style="color: #0000ff;"> object</span><span>&gt; BrokerProperties { <span><span style="color: #0000ff;"> get</span><span>; <span><span style="color: #0000ff;"> set</span><span>; }&nbsp;<br />&nbsp;&nbsp;<span style="color: blue;">public</span><span>&nbsp;<span style="color: black;"><span style="color: blue;">bool<span style="color: black;">&nbsp;IsBodyBase64 { <span style="color: blue;"> get<span style="color: black;">; <span style="color: blue;"> set<span style="color: black;">; }<br />&nbsp;&nbsp;<span style="color: blue;">public&nbsp;<span style="color: black;">Dictionary&lt;<span style="color: blue;">string<span style="color: black;">, <span style="color: blue;"> object<span style="color: black;">&gt; UserProperties { <span style="color: blue;"> get<span style="color: black;">; <span style="color: blue;"> set<span style="color: black;">;&nbsp;}<br /> }<br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">&nbsp;<span style="font-size: 12px;">&nbsp;</span><span style="font-size: 12px;">You don&rsquo;t need to send the fields that you don&rsquo;t use. So if you are only sending a text payload you can just send a message like this:</span></p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> using<span style="color: black;">&nbsp;(<span style="color: blue;">var<span style="color: black;">&nbsp;requestStream = webClient.GetRequestStream())<br />{<br />&nbsp; <span style="color: blue;"> var<span style="color: black;">&nbsp;bodyBytes = <span style="color: #2b91af;"> Encoding<span style="color: black;">.Default.GetBytes(<span style="color: #a31515;"> "[{\"Body\":\"Message1\"}]"<span style="color: black;">&nbsp;);&nbsp;</span></span></span></span></span></span></span></span></span></span><br /> <span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #a31515;"><span style="color: black;">&nbsp; requestStream.Write(bodyBytes, 0, bodyBytes.Length); </span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #a31515;"><span style="color: black;">}<br /> <br /></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">&nbsp;<span style="font-size: 12px;">&nbsp;</span><span style="font-size: 12px;">This is equivalent to the Non-Batch Http Send. The receive code path does not change. You would just receive it like you would receive a regular text message (no need to deserialize, we default to text serialization).</span></p>
<p class="MsoNormal"><span style="font-size: 12px;"><br /></span></p>
<p class="MsoNormal">However in the past you have been able to set some Broker Properties in your Http message (such as CorrelationId, <span style="font-size: 9.5pt; line-height: 107%; font-family: Consolas; color: black; background: white;">SessionId</span><span style="font-size: 9.5pt; line-height: 107%; font-family: Consolas; color: black;">, <span style="background: white;">PartitionKey</span>, <span style="background: white;">TimeToLiveTimeSpan</span>, etc)</span> and we still support that. You can just set those as part of the BrokerProperties Dictionary and we will set them in the BrokeredMessage.</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> using<span style="color: black;">&nbsp;(<span style="color: blue;">var<span style="color: black;">&nbsp;requestStream = request.GetRequestStream())<br />{<br />&nbsp; <span style="color: blue;"> var<span style="color: black;">&nbsp;bodyBytes = <span style="color: #2b91af;"> Encoding<span style="color: black;">.Default.GetBytes(<span style="color: #a31515;"> @"[{""Body"":""SGVsbG8="",""BrokerProperties"":[{""Name"":""CorrelationId"",""Value"":""32119834-65f3-48c1-b366-619df2e4c400""}]}]"<span style="color: black;"> ); </span></span></span></span></span></span></span></span></span></span><br /> <span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #a31515;"><span style="color: black;">&nbsp; requestStream.Write(bodyBytes, 0, bodyBytes.Length); </span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #a31515;"><span style="color: black;">}<br /> <br /></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">And again if you want to set your own Properties you can add them to the UserProperties Dictionary and we will populate the BrokeredMessage.Properties with them</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> using<span style="color: black;">&nbsp;( <span style="color: blue;"> var<span style="color: black;">&nbsp;requestStream = request.GetRequestStream())<br />{<br />&nbsp; <span style="color: blue;"> var<span style="color: black;">&nbsp;bodyBytes = <span style="color: #2b91af;"> Encoding<span style="color: black;">.Default.GetBytes(<span style="color: #a31515;">@"[{""Body"":""SGVsbG8="",""UserProperties"":[{""Name"":""ColorValue"",""Value"":""Black""}]}]"<span style="color: black;"> ); </span></span></span></span></span></span></span></span></span></span> <br /><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #a31515;"><span style="color: black;">&nbsp; requestStream.Write(bodyBytes, 0, bodyBytes.Length); </span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #a31515;"><span style="color: black;">}<br /> <br /></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">And finally if you want to send an arbitrary object instead of plain text you can do it by using the IsBodyBase64 setting.</p>
<p class="MsoNormal">Here is an example of sending an object of a custom class called <strong>MyTestObject</strong>.</p>
<p class="MsoNormal">1)</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: black;"> [Serializable]<br /><span style="color: blue;"> public<span style="color: black;">&nbsp;<span style="color: blue;"> class<span style="color: black;">&nbsp;<span style="color: #2b91af;"> MyTestObject<span style="color: black;"> <br />{<br />&nbsp;&nbsp;<span style="color: blue;"> public<span style="color: black;">&nbsp;<span style="color: blue;">string<span style="color: black;">&nbsp;Name { <span style="color: blue;"> get<span style="color: black;"> ; <span style="color: blue;"> set<span style="color: black;"> ; }<br />&nbsp;&nbsp;<span style="color: blue;"> public<span style="color: black;">&nbsp;<span style="color: #2b91af;">DateTime<span style="color: black;">&nbsp;TimeStamp { <span style="color: blue;"> get<span style="color: black;"> ; <span style="color: blue;"> set<span style="color: black;"> ;&nbsp;}&nbsp;<br /> }<br /> <br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">2)</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> var<span style="color: black;">&nbsp;arbitraryObject = <span style="color: blue;"> new<span style="color: black;">&nbsp;<span style="color: #2b91af;">SerializationHelper<span style="color: black;">.<span style="color: #2b91af;">MyTestObject<span style="color: black;">() { Name = msgBodies[0], TimeStamp = <span style="color: #2b91af;"> DateTime<span style="color: black;">.Now };<br /><span style="color: blue;"> var<span style="color: black;">&nbsp;jsonBody = <span style="color: #2b91af;"> PayloadHelper<span style="color: black;"> .JsonifyObject(arbitraryObject); <br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">3)</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: green;"> // Generates the Json payload with Json.net Serialization<span style="color: black;"> <br /><span style="color: blue;"> public<span style="color: black;">&nbsp;<span style="color: blue;">static<span style="color: black;">&nbsp;<span style="color: blue;">string<span style="color: black;">&nbsp;JsonifyObject(<span style="color: blue;">object<span style="color: black;">&nbsp;serializableObject)<br />{<br />&nbsp;&nbsp;<span style="color: blue;">string<span style="color: black;">&nbsp;objectEncodedBytes;<br />&nbsp;&nbsp;<span style="color: blue;">using<span style="color: black;">&nbsp;(<span style="color: blue;"> var<span style="color: black;">&nbsp;ms = <span style="color: blue;"> new<span style="color: black;">&nbsp;<span style="color: #2b91af;">MemoryStream<span style="color: black;">())<br />&nbsp;&nbsp;{<br />&nbsp; &nbsp;<span style="color: blue;"> var<span style="color: black;">&nbsp;bf = <span style="color: blue;"> new<span style="color: black;">&nbsp;<span style="color: #2b91af;">BinaryFormatter<span style="color: black;">();<br />&nbsp;&nbsp;&nbsp;&nbsp;bf.Serialize(ms, serializableObject);<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;objectEncodedBytes = <span style="color: #2b91af;"> Convert<span style="color: black;">.ToBase64String(ms.ToArray());<br />&nbsp;&nbsp;<br />&nbsp;&nbsp;<span style="color: blue;">&nbsp; var<span style="color: black;">&nbsp;jsonObject = <span style="color: blue;"> new<span style="color: black;">&nbsp;<span style="color: #2b91af;">SerializationHelper<span style="color: black;">.<span style="color: #2b91af;">HttpBrokeredMessage<span style="color: black;">() { Body = objectEncodedBytes, IsBodyBase64 = <span style="color: blue;"> true<span style="color: black;">&nbsp;};&nbsp;<br />&nbsp;&nbsp;<span style="color: blue;">&nbsp; var<span style="color: black;">&nbsp;batch = <span style="color: blue;"> new<span style="color: black;">[] { jsonObject };<br /><br />&nbsp;&nbsp;<span style="color: blue;">&nbsp; return<span style="color: black;">&nbsp;<span style="color: #2b91af;">JsonConvert<span style="color: black;">.SerializeObject(batch); </span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="color: green;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;">}<br /> <br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">As you can see we do the following:</p>
<p class="MsoListParagraphCxSpFirst" style="text-indent: -.25in;">&nbsp;</p>
<ul>
<li><span style="text-indent: -0.25in; font-size: 12px;">Define the class of our custom object</span></li>
<li><span style="text-indent: -0.25in; font-size: 12px;">We create a new object of this class</span></li>
<li><span style="text-indent: -0.25in; font-size: 12px;">We JsonifyTheObject (This creates the message that we will insert into a batch)</span></li>
</ul>
<p><span style="text-indent: -0.25in;">-&nbsp;Use BinaryFormatter (from System.Runtime.Serialization) to serialize our object.</span><br /><span style="font-size: 12px; text-indent: -0.25in;">-&nbsp;Convert that to a Base64 Encoded string (This is the body)</span><br /><span style="font-size: 12px; text-indent: -0.25in;">-&nbsp;Create an HttpBrokeredMessage that has this newly created body</span><br /><span style="font-size: 12px; text-indent: -0.25in;">-&nbsp;Serialize this to Json with NewtonSoft.JsonConvert</span></p>
<ul>
<li><span style="text-indent: -0.25in; font-size: 12px;">Now we have a json string that contains one message. We can do the same with the rest of our messages and send them as a Json array &ldquo;[message1, message2&hellip;]&rdquo;</span></li>
</ul>
<p>&nbsp;</p>
<p class="MsoNormal">Now the interesting thing of sending binary messages is that when we are receiving them we can just do a Receive&lt;MyTestObject&gt; and the .Net client will do all the hard work of deserialization for you. So the code in the receive path is a lot simpler :)</p>
<h2>Accepted types for UserProperties</h2>
<p><span style="font-size: 11.0pt; font-family: 'Calibri',sans-serif; color: black;">We accept the same types used for regular Rest Send:</span></p>
<p style="margin-top: 0in; margin-right: 0in; margin-bottom: .0001pt; margin-left: .5in; text-indent: -.25in;"><span style="font-size: 11.0pt; font-family: Symbol; color: black;">&middot;<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><span style="font-size: 11.0pt; font-family: 'Calibri',sans-serif; color: black;">Boolean values</span></p>
<p style="margin-top: 0in; margin-right: 0in; margin-bottom: .0001pt; margin-left: .5in; text-indent: -.25in;"><span style="font-size: 11.0pt; font-family: Symbol; color: black;">&middot;<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><span style="font-size: 11.0pt; font-family: 'Calibri',sans-serif; color: black;">Null</span></p>
<p style="margin-top: 0in; margin-right: 0in; margin-bottom: .0001pt; margin-left: .5in; text-indent: -.25in;"><span style="font-size: 11.0pt; font-family: Symbol; color: black;">&middot;<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><span style="font-size: 11.0pt; font-family: 'Calibri',sans-serif; color: black;">Integers</span></p>
<p style="margin-top: 0in; margin-right: 0in; margin-bottom: .0001pt; margin-left: .5in; text-indent: -.25in;"><span style="font-size: 11.0pt; font-family: Symbol; color: black;">&middot;<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><span style="font-size: 11.0pt; font-family: 'Calibri',sans-serif; color: black;">Doubles</span></p>
<p style="margin-top: 0in; margin-right: 0in; margin-bottom: .0001pt; margin-left: .5in; text-indent: -.25in;"><span style="font-size: 11.0pt; font-family: Symbol; color: black;">&middot;<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><span style="font-size: 11.0pt; font-family: 'Calibri',sans-serif; color: black;">Strings</span></p>
<p class="MsoNormal">&nbsp;</p>
<h2>Sample receive code</h2>
<p class="MsoNormal">&nbsp;<span style="font-size: 12px;">The receive code path has not changed at all. From the .Net client you can just do a Receive and get back your message. From Http you can use code similar to this:</span></p>
<p class="MsoNormal">For Text:</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> using<span style="color: black;">&nbsp;(<span style="color: blue;"> var<span style="color: black;">&nbsp;response = (<span style="color: #2b91af;"> HttpWebResponse<span style="color: black;"> )readRequest.GetResponse())&nbsp;<br />{<br />&nbsp;<span style="color: blue;">&nbsp;if<span style="color: black;">&nbsp;(response.StatusCode == <span style="color: #2b91af;"> HttpStatusCode<span style="color: black;"> .OK)<br />&nbsp;&nbsp;{<br />&nbsp; &nbsp;<span style="color: blue;"> using<span style="color: black;">&nbsp;(<span style="color: blue;">var<span style="color: black;">&nbsp;content = response.GetResponseStream())<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;"> var<span style="color: black;">&nbsp;reader = <span style="color: blue;"> new<span style="color: black;">&nbsp;<span style="color: #2b91af;">StreamReader<span style="color: black;"> (content);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;"> string<span style="color: black;"> receivedMessage = reader.ReadToEnd();</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="font-size: 12px;">&nbsp; &nbsp; }</span></p>
<p style="font-family: Courier New;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"> &nbsp;&nbsp;}<br /> }<br /> <br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">For Binary objects:</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> using<span style="color: black;">&nbsp;(<span style="color: blue;"> var<span style="color: black;">&nbsp;response = (<span style="color: #2b91af;"> HttpWebResponse<span style="color: black;"> )readRequest.GetResponse())<br />{<br />&nbsp;<span style="color: blue;">&nbsp;if<span style="color: black;">&nbsp;(response.StatusCode == <span style="color: #2b91af;"> HttpStatusCode<span style="color: black;"> .OK)<br />&nbsp;&nbsp;{<br />&nbsp; &nbsp;<span style="color: blue;"> using<span style="color: black;">&nbsp;(<span style="color: blue;"> var<span style="color: black;">&nbsp;content = response.GetResponseStream())<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;"> byte<span style="color: black;">[] receivedBytes = <span style="color: #2b91af;"> SerializationHelper<span style="color: black;">.ReadBytesFromStream(content);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;"> object<span style="color: black;">&nbsp;receivedObject = <span style="color: #2b91af;"> SerializationHelper<span style="color: black;">.ByteArray2Object(receivedBytes);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;"> var<span style="color: black;">&nbsp;received = (<span style="color: #2b91af;">SerializationHelper<span style="color: black;">.<span style="color: #2b91af;">MyTestObject<span style="color: black;">)receivedObject;</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"> &nbsp;&nbsp;&nbsp;&nbsp;}<br /> &nbsp;&nbsp;}<br /> }<br /> <br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<h1><span style="font-size: 9.5pt; line-height: 107%; font-family: Consolas; color: black; background: white;">}</span></h1>
<h1><span style="font-size: 9.5pt; line-height: 107%; font-family: Consolas; color: black;">&nbsp;</span></h1>
<h2>How to debug any problems with Batch Send?</h2>
<p class="MsoPlainText" style="margin-left: .5in; text-indent: -.25in;">1)<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>If when you receive the message you receive one <strong>IEnumerable</strong> object with <strong>n</strong> elements in it that means you are not going through the Batch Send pipeline. Double check if the Request content type is correct. It should be "application/vnd.microsoft.servicebus.json"</p>
<p class="MsoListParagraph" style="text-indent: -.25in;">2)<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>If you get a 400 error when you send then that means something is wrong with your message. You can use this code to get more information from the web exception:</p>
<p class="MsoNormal">&nbsp;</p>
<table style="border-color: #000000; border-width: 0px;" border="1">
<tbody>
<tr>
<td>
<p style="font-family: Courier New;"><span style="color: blue;"> static<span style="color: black;">&nbsp;<span style="color: blue;"> string<span style="color: black;">&nbsp;GetErrorFromException(<span style="color: #2b91af;"> WebException<span style="color: black;">&nbsp;webExcp)<br />{<br />&nbsp;&nbsp;<span style="color: blue;"> var<span style="color: black;">&nbsp;httpResponse = (<span style="color: #2b91af;"> HttpWebResponse<span style="color: black;"> )webExcp.Response;<br />&nbsp;&nbsp;<span style="color: blue;"> var<span style="color: black;">&nbsp;stream = httpResponse.GetResponseStream();<br />&nbsp;&nbsp;<span style="color: blue;"> byte<span style="color: black;">[] receivedBytes = <span style="color: #2b91af;"> SerializationHelper<span style="color: black;"> .ReadBytesFromStream(stream);<br />&nbsp;&nbsp;<span style="color: blue;"> return<span style="color: black;">&nbsp;<span style="color: #2b91af;">Encoding<span style="color: black;">.UTF8.GetString(receivedBytes); </span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
<p style="font-family: Courier New;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;"><span style="color: blue;"><span style="color: black;"><span style="color: #2b91af;"><span style="color: black;">}<br /> <br /></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal">&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>What does a performance developer do at Microsoft?</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/what-does-a-performance-developer-do-at-microsoft</link>
      <pubDate>Thu, 15 Jan 2015 18:31:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2015/01/15/what-does-a-performance-developer-do-at-microsoft/</guid>
      <description><![CDATA[&nbsp;Someone was just asking me this question the other day so I figured that I would answer it...]]></description>
      <content:encoded><![CDATA[<p>&nbsp;Someone was just asking me this question the other day so I figured that I would answer it here for people that are interested in this role inside and outside the company.</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">I have been a performance developer at Microsoft for a little more than 4 years. During these years I have done performance investigations for Visual Studio (Workflow Designer), .Net Framework (Windows Communication Foundation), Azure Service Bus, Azure Event Hub and Azure Api Management. And still some friends at Microsoft are not sure what I do in my day to day work.</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">Typically Microsoft used to have 3 clearly differentiated roles (This has been changing lately): Program Managers, Software Developer Engineers and Software Developer Engineer in Test. Some SDETs specialize in UI testing or Stress testing.&nbsp;The PM role has a couple specializations: Release PM or Feature PM. The Developer has a few specializations as well: one of these specializations is the <strong>Performance Developer</strong>.</p>
<p class="MsoNormal">We are developers that focus on finding, analyzing and fixing performance problems (throughput, latency or scalability). We also work on adding performance features and since performance and scalability are so closely related we are also pulled-in to work on issues that might affect how a system behaves at scale. So part of our day can be spent looking at a profile or we can be looking at crash dumps to figure out why a given product is crashing when it&rsquo;s being hit by thousands of requests.</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">I personally work in a group called "Azure Application Fundamentals". This team owns the Stress team, the Performance team and the Servicing team for the Azure Application group. What this means is that any team that is part of the Azure Application can ask us to help them with performance investigations.</p>
<p class="MsoNormal">This is a list of some things we do as part of our daily work:</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal"><strong>Measure scenarios:</strong> Work with the feature team to identify main scenarios that we want to measure, establish goals, test authoring, ensure the tests are getting executed regularly and that the results are reported somewhere.</p>
<p class="MsoNormal"><strong>Regression Prevention</strong>: Make sure that the performance of the main scenarios improves as time goes by.</p>
<p class="MsoNormal"><strong>Performance Analysis</strong>: Jump in and analyze the performance of any feature important to the team and figure out why it&rsquo;s not meeting goals.</p>
<p class="MsoNormal"><strong>Optimization</strong>: Fix the performance problems or implement performance features to improve the&nbsp;performance of the product.</p>
<p class="MsoNormal"><strong>Education</strong>: Teach the feature team what things are not good for performance and pretty much make sure they can do any of the previous steps themselves. Also share what you learn about the different tools used to measure and analyze performance problems.</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">There is a lot of case by case investigation but something important is that we try to make sure that the teams that are under our purview are measuring and reporting all their performance scenarios to a centralized Reporting system. This makes it easier to understand how the team is related to performance. It makes it very clear to understand when things are getting better or worse.</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">I find a couple of things interesting about this role. It lets even junior developers learn about performance, investigate profiles and memory dumps&nbsp;and basically grow until they become more knowledgeable about performance. In my experience not a lot of developers know what to do when something is slow. Having a specialized role encourages sharing of this information.</p>
<p class="MsoNormal">Also it's not very common for a team to be interested in investing in performance during the early parts of the development cycle. They want to have something to show as soon as possible. However what I've seen is that if you leave the performance as the last thing you do you will not be able to fix much. You will find that your design has certain performance characteristics that are simply too risky to change at the end of the lifecycle of the product. You might also find that everything is slow: there is no clear "smoking bullet" to change. This can be because you have used pervasive slow techniques across your entire product. This causes in my opinion a lot of teams to just ship something even though they know it is slow. Having someone from outside focusing on performance helps to avoid this.</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">So for me it&rsquo;s been a very cool experience and I highly recommend it!</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">If you are interested in performance here are a few blogs of other Performance Engineers at Microsoft:</p>
<p class="MsoNormal"><span lang="ES-MX"><a href="https://blogs.msdn.com/b/vancem/"><span lang="EN-US">Vance Morrison</span></a></span></p>
<p class="MsoNormal"><span lang="ES-MX"><a href="https://blogs.msdn.com/b/ricom/"><span lang="EN-US">Rico Mariani</span></a> - </span></p>
<p class="MsoNormal"><span lang="ES-MX"><a href="https://blogs.msdn.com/b/sajay/"><span lang="EN-US">Sajay Antony</span></a></span>- His blog has not been updated in a while but he has some neat projects in his <a href="https://github.com/SajayAntony">Github</a></p>
<p class="MsoNormal"><span lang="ES-MX"><a href="https://blogs.msdn.com/b/dmetzgar/"><span lang="EN-US">Dustin Metzgar</span></a></span></p>
<p class="MsoNormal"><a href="https://randomascii.wordpress.com/">Bruce Dawson</a> - Ex Msft &ndash; has fantastic posts about xperf</p>]]></content:encoded>
    </item>
    <item>
      <title>Using Service Bus / EventHub from Android devices</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/using-service-bus-eventhub-from-android-devices</link>
      <pubDate>Wed, 07 Jan 2015 16:41:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2015/01/07/using-service-bus-eventhub-from-android-devices/</guid>
      <description><![CDATA[Last summer we had Jimmy Campbell join the Fundamentals team for a couple of months as part of his...]]></description>
      <content:encoded><![CDATA[<p>Last summer we had Jimmy Campbell join the Fundamentals team for a couple of months as part of his internship with Microsoft.</p>
<p>I was assigned as his mentor and since I was working for the Azure Service Bus team I chose his project to be &ldquo;Amqp for Android&rdquo;.</p>
<p>Jimmy did such a fast job that after about 7 weeks we had to find another project! :)</p>
<p>So here is the github link to the work he did:</p>
<p><a href="https://github.com/AppPlatPerf/qpid-proton/tree/AndroidProton">https://github.com/AppPlatPerf/qpid-proton/tree/AndroidProton<br /></a></p>
<p>He basically solved all the hurdles so that people that want to use Service Bus / Event Hub from Android devices can do it very easily. It builds on top of the Proton-C Amqp library.</p>
<p>Hope it's useful for people out there!</p>]]></content:encoded>
    </item>
    <item>
      <title>Improving Latency in Http Proxy scenario</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/improving-latency-in-http-proxy-scenario</link>
      <pubDate>Fri, 05 Dec 2014 17:23:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2014/12/05/improving-latency-in-http-proxy-scenario/</guid>
      <description><![CDATA[Stream to stream copying is a scenario that is not straightforward to implement. It is especially...]]></description>
      <content:encoded><![CDATA[<p><span style="font-size: 12px;">Stream to stream copying is a scenario that is not straightforward to implement. It is especially important in a Proxy scenario.</span></p>
<h2>Proxy</h2>
<p class="MsoNormal">Let&rsquo;s start from the beginning. What is a proxy?</p>
<p class="MsoNormal"><em>A <strong>server</strong> that acts as an intermediary for requests from <strong>clients</strong> seeking resources from other <strong>servers</strong></em> (<a href="https://en.wikipedia.org/wiki/Proxy_server">Wikipedia</a>)</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">There are many reasons why you would want to have a Proxy server. The intermediary can add value to the request or to the response. For example it can make sure your backend server is not getting too many requests. It can also add caching so that your backend server is not even called. Other examples of value add are: security, compression, encryption, load balancing, etc.</p>
<p class="MsoNormal">For the past few months I've been helping out a <a href="https://azure.microsoft.com/en-us/services/api-management/">team</a> in Microsoft that has one of these services.</p>
<div style="border: none; border-bottom: solid windowtext 1.0pt; padding: 0in 0in 1.0pt 0in;">
<p class="MsoNormal" style="border: none; padding: 0in;">As you can imagine it is critical that we ensure that the response is being delivered to the user as fast as possible. We call this response time <strong>latency</strong>. In a proxy scenario it is very important it is as low as possible because the backend is the one doing most of the work. The proxy should be a thin layer.</p>
<p class="MsoNormal" style="border: none; padding: 0in;">&nbsp;</p>
</div>
<p class="MsoNormal">&nbsp;The default implementation of a proxy would be something like this:</p>
<p class="MsoNormal"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/47/37/0564.image001.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-47-37/0564.image001.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/47/37/0564.image001.png" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-47-37/0564.image001.png" alt="" border="0" /></a></p>
<pre>1) The Proxy receives the request<br />2) The Proxy makes a request to the backend<br />3) The Proxy gets the response from the backend<br />4) The Proxy passes this response back to the user.</pre>
<p class="MsoNormal">So the Proxy will have two streams for each request. One stream for the Backend Response and one stream for the Proxy Response that we are generating. And as we discussed above it should be copying data from the origin (Backend response) to the destination (Proxy response) as fast as possible.</p>
<p class="MsoNormal">The default way to copy data from one stream in .Net is something like this:</p>
<div style="border: solid windowtext 1.0pt; padding: 1.0pt 4.0pt 1.0pt 4.0pt; background: white;">
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: blue;">await</span><span style="font-family: Consolas; color: black;">&nbsp;backendContent.CopyToAsync(context.Response.OutputStream);</span></pre>
</div>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">This implementation has a few flaws:</p>
<p class="MsoListParagraph" style="text-indent: -.25in;">1)<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>It allocates too much. Like I&rsquo;ve mentioned before Stream.CopyTo allocates an 80k buffer each time it is called. So the proxy would be allocating an 80k buffer regardless of the stream size for each request! This might not be a problem if it&rsquo;s something that you only do once every month. But for a Proxy server this is not acceptable. Too much memory pressure.</p>
<p class="MsoNormal">There is a version of CopyToAsync that allows you to control the buffer size:</p>
<div style="border: solid windowtext 1.0pt; padding: 1.0pt 4.0pt 1.0pt 4.0pt; background: white;">
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: blue;">await</span><span style="font-family: Consolas; color: black;">&nbsp;backendContent.CopyToAsync(context.Response.OutputStream, _readChunkSize);</span></pre>
</div>
<pre style="background: white;"><span style="font-family: Consolas; color: black;">&nbsp;</span></pre>
<p class="MsoListParagraphCxSpFirst" style="text-indent: -.25in;">2)<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>The problem with this method overload is that you need the ability of passing your own buffer. Otherwise every request will allocate memory. You need to be able to pool memory so that you don&rsquo;t allocate too much. See my previous <a href="https://blogs.msdn.com/b/shacorn/archive/2014/11/12/optimizing-memory-footprint-compression-in-net-4-5.aspx">blog</a> on how to do that.</p>
<p class="MsoListParagraphCxSpLast">&nbsp;</p>
<p class="MsoListParagraphCxSpLast">There is another problem with both implementations.</p>
<p class="MsoNormal"><strong>3) They are slow</strong></p>
<p class="MsoNormal">Let&rsquo;s measure the 3<sup>rd</sup> point. I grabbed a couple of Azure VMs and did this:</p>
<pre>1) Deploy Backend in Azure West (All it does is return a file with an arbitrary size)<br />2) Deploy Proxy in Azure East (All it does is call backend and return the same body)<br />3) Call Proxy from my dev box.</pre>
<p class="MsoNormal">I used Fiddler to call my Proxy and measured how long it takes to download a 50MB file through it:</p>
<p class="MsoNormal"><span style="font-size: 8.5pt; line-height: 107%; font-family: 'Lucida Console';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Overall Elapsed:&nbsp;&nbsp;&nbsp;&nbsp; 0:00:24.021</span></p>
<p class="MsoNormal">It takes more than 20 seconds to download a 50 MB file. We&rsquo;ll see how much we can improve this.</p>
<p class="MsoNormal">&nbsp;</p>
<h2>Reason of the problem</h2>
<p class="MsoNormal">Let&rsquo;s look at the implementation of Stream.CopyTo (which calls CopyToAsync:</p>
<div style="border: solid windowtext 1.0pt; padding: 1.0pt 4.0pt 1.0pt 4.0pt; background: white;">
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">private</span><span style="font-family: Consolas; color: black;">&nbsp;</span><span style="font-family: Consolas; color: blue;">async</span><span style="font-family: Consolas; color: black;">&nbsp;</span><span style="font-family: Consolas; color: #2b91af;">Task</span><span style="font-family: Consolas; color: black;">&nbsp;CopyToAsyncInternal(</span><span style="font-family: Consolas; color: #2b91af;">Stream</span><span style="font-family: Consolas; color: black;">&nbsp;destination,&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;bufferSize,&nbsp;CancellationToken&nbsp;cancellationToken)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">[]&nbsp;buffer&nbsp;=&nbsp;</span><span style="font-family: Consolas; color: blue;">new</span><span style="font-family: Consolas; color: black;">&nbsp;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">[bufferSize];</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">while</span><span style="font-family: Consolas; color: black;">&nbsp;(</span><span style="font-family: Consolas; color: blue;">true</span><span style="font-family: Consolas; color: black;">)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;num&nbsp;=&nbsp;</span><span style="font-family: Consolas; color: blue;">await</span><span style="font-family: Consolas; color: black;">&nbsp;</span><span style="font-family: Consolas; color: blue;">this</span><span style="font-family: Consolas; color: black;">.ReadAsync(buffer,&nbsp;0,&nbsp;buffer.Length,&nbsp;cancellationToken).ConfigureAwait(</span><span style="font-family: Consolas; color: blue;">false</span><span style="font-family: Consolas; color: black;">);</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;bytesRead;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">if</span><span style="font-family: Consolas; color: black;">&nbsp;((bytesRead&nbsp;=&nbsp;num)&nbsp;!=&nbsp;0)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">await</span><span style="font-family: Consolas; color: black;">&nbsp;destination.WriteAsync(buffer,&nbsp;0,&nbsp;bytesRead,&nbsp;cancellationToken).ConfigureAwait(</span><span style="font-family: Consolas; color: blue;">false</span><span style="font-family: Consolas; color: black;">);</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">else</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">break</span><span style="font-family: Consolas; color: black;">;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
</div>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">As you can see it always dominated by the slowest part (reader or writer)</p>
<pre>* If the writer takes too long to write, the reader cannot read more data.<br />* There is only one pending write on the wire.</pre>
<p class="MsoNormal">So even though it is not blocking threads (it&rsquo;s using await) it will not be as fast as possible. The underlying stream supports multiple writes on it. So there is no reason why we need to wait until it finishes writing it before we start writing another one.</p>
<p class="MsoNormal"><strong>Here is an example:</strong></p>
<p class="MsoNormal">If your writes take 10 milliseconds to write to the wire you will be bound by the amount of data you can push every 10 milliseconds. So if each write is only pushing a 4K buffer you will be able to send only 400K data per second (4K * 10 * 10).</p>
<p class="MsoNormal">If you are able to read much faster than 400K/second this is not acceptable. What you want is to have the ability of scheduling more than one write at a time. This way you will be able to saturate your network link.</p>
<p class="MsoNormal">&nbsp;</p>
<h2>Proposal: Consumer &ndash; Producer pattern</h2>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">My proposal to fix this is to decouple the reads from the writes. Of course we can only write what we have read but read and write operations happen at different rates. So I think it makes sense to make them independent.</p>
<p class="MsoNormal">A way to do this is to follow the Consumer/Producer pattern.</p>
<p class="MsoListParagraphCxSpFirst" style="text-indent: -.25in;">1)<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>We have a queue where the Producer (the <span style="background: lime;">reader</span>) puts buffers as soon as he reads data.</p>
<p class="MsoListParagraphCxSpLast" style="text-indent: -.25in;">2)<span style="font: 7.0pt 'Times New Roman';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>Then we have a Consumer (the <span style="background: lime;">writer</span>) that grabs buffers as they become available and schedules a write to the wire. Note that it is critical that the consumer does not wait until the write is done before continuing. As mentioned before the HttpResponse OutputStream supports multiple writes.</p>
<p class="MsoNormal">These two will be running in independent threads and they will stop once the <strong>input</strong> stream is done and when we have written all the data to the <strong>output</strong> stream.</p>
<h3>Read Loop</h3>
<div style="border: solid windowtext 1.0pt; padding: 1.0pt 4.0pt 1.0pt 4.0pt; background: white;">
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: #2b91af;">Action</span><span style="font-family: Consolas; color: black;">&nbsp;readLoop&nbsp;=&nbsp;</span><span style="font-family: Consolas; color: blue;">async</span><span style="font-family: Consolas; color: black;">&nbsp;()&nbsp;=&gt;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">while</span><span style="font-family: Consolas; color: black;">&nbsp;(</span><span style="font-family: Consolas; color: blue;">true</span><span style="font-family: Consolas; color: black;">)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Now&nbsp;wait&nbsp;until&nbsp;there&nbsp;is&nbsp;a&nbsp;free&nbsp;buffer&nbsp;to&nbsp;read&nbsp;into.</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ArraySegment&lt;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">&gt;&nbsp;freeBuffer&nbsp;=&nbsp;_freeReadBufferQueue.Take();</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">[]&nbsp;readBuffer&nbsp;=&nbsp;freeBuffer.Array;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;readBufferSize&nbsp;=&nbsp;readBuffer.Length;</span></pre>
<pre style="background: white; border: none; padding: 0in;">&nbsp;</pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Fill&nbsp;the&nbsp;read&nbsp;buffer&nbsp;before&nbsp;enqueueing&nbsp;it&nbsp;for&nbsp;writing</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;readTotal&nbsp;=&nbsp;0;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;readImmediate;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">do</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readImmediate&nbsp;=&nbsp;</span><span style="font-family: Consolas; color: blue;">await</span><span style="font-family: Consolas; color: black;">&nbsp;input.ReadAsync(readBuffer,&nbsp;readTotal,&nbsp;readBufferSize&nbsp;-&nbsp;readTotal);</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;readTotal&nbsp;+=&nbsp;readImmediate;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">while</span><span style="font-family: Consolas; color: black;">&nbsp;(readImmediate&nbsp;&gt;&nbsp;0&nbsp;&amp;&amp;&nbsp;readTotal&nbsp;&lt;&nbsp;readBufferSize);</span></pre>
<pre style="background: white; border: none; padding: 0in;">&nbsp;</pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Enqueue&nbsp;it&nbsp;in&nbsp;the&nbsp;dataQueue&nbsp;for&nbsp;this&nbsp;request</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dataQueue.Add(</span><span style="font-family: Consolas; color: blue;">new</span><span style="font-family: Consolas; color: black;">&nbsp;ArraySegment&lt;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">&gt;(readBuffer,&nbsp;0,&nbsp;readTotal));</span></pre>
<pre style="background: white; border: none; padding: 0in;">&nbsp;</pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">if</span><span style="font-family: Consolas; color: black;">&nbsp;(readTotal&nbsp;==&nbsp;0)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Done&nbsp;reading.&nbsp;Bail&nbsp;out&nbsp;of&nbsp;the&nbsp;read&nbsp;loop</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">break</span><span style="font-family: Consolas; color: black;">;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">};</span></pre>
</div>
<ol>
<li>The reader takes a buffer from the &ldquo;Free buffers queue&rdquo;. If this queue has a buffer it means there is space for him to read. If the queue is empty it means all of our buffers are being used.</li>
<li>Then it fills this buffer (note the do-while) until there is no more content or it&rsquo;s out of space.</li>
<li>Then it adds this buffer to another queue. The dataqueue. This queue is the one that is read by the consumer.</li>
<li>When it&rsquo;s done reading we break out of the loop. Otherwise it starts at 1 again.</li>
</ol>
<h3 class="MsoNormal"><span style="font-size: 1.17em;">Write Loop</span></h3>
<div style="border: solid windowtext 1.0pt; padding: 1.0pt 4.0pt 1.0pt 4.0pt; background: white;">
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: #2b91af;">Action</span><span style="font-family: Consolas; color: black;">&nbsp;writeLoop&nbsp;=&nbsp;</span><span style="font-family: Consolas; color: blue;">async</span><span style="font-family: Consolas; color: black;">&nbsp;()&nbsp;=&gt;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">while</span><span style="font-family: Consolas; color: black;">&nbsp;(</span><span style="font-family: Consolas; color: blue;">true</span><span style="font-family: Consolas; color: black;">)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ArraySegment&lt;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">&gt;&nbsp;dataArraySegment&nbsp;=&nbsp;dataQueue.Take();</span></pre>
<pre style="background: white; border: none; padding: 0in;">&nbsp;</pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">int</span><span style="font-family: Consolas; color: black;">&nbsp;dataRead&nbsp;=&nbsp;dataArraySegment.Count;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">[]&nbsp;dataBuffer&nbsp;=&nbsp;dataArraySegment.Array;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">if</span><span style="font-family: Consolas; color: black;">&nbsp;(dataRead&nbsp;==&nbsp;0)</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;If&nbsp;the&nbsp;dataQueue&nbsp;has&nbsp;no&nbsp;data&nbsp;it&nbsp;means&nbsp;we&nbsp;have&nbsp;reached&nbsp;the&nbsp;end&nbsp;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;of&nbsp;the&nbsp;input&nbsp;stream.&nbsp;Time&nbsp;to&nbsp;bail&nbsp;out&nbsp;of&nbsp;the&nbsp;write&nbsp;loop</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_freeReadBufferQueue.Add(</span><span style="font-family: Consolas; color: blue;">new</span><span style="font-family: Consolas; color: black;">&nbsp;ArraySegment&lt;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">&gt;(dataBuffer));</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">break</span><span style="font-family: Consolas; color: black;">;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;">&nbsp;</pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Schedule&nbsp;async&nbsp;write.&nbsp;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Make&nbsp;sure&nbsp;you&nbsp;don't&nbsp;wait&nbsp;until&nbsp;it's&nbsp;done&nbsp;before&nbsp;continuing&nbsp;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output.BeginWrite(dataBuffer,&nbsp;0,&nbsp;dataRead,&nbsp;(iar)&nbsp;=&gt;</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">try</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output.EndWrite(iar);</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: blue;">finally</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Consolas; color: green;">//&nbsp;Enqueue&nbsp;the&nbsp;buffer&nbsp;back&nbsp;to&nbsp;the&nbsp;pool&nbsp;so&nbsp;that&nbsp;we&nbsp;can&nbsp;read&nbsp;more&nbsp;data</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_freeReadBufferQueue.Add(</span><span style="font-family: Consolas; color: blue;">new</span><span style="font-family: Consolas; color: black;">&nbsp;ArraySegment&lt;</span><span style="font-family: Consolas; color: blue;">byte</span><span style="font-family: Consolas; color: black;">&gt;(dataBuffer));</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;</span><span style="font-family: Consolas; color: blue;">null</span><span style="font-family: Consolas; color: black;">);</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;}</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">&nbsp;&nbsp;&nbsp;&nbsp;allWritesHaveBeenEnqueued.SetResult(</span><span style="font-family: Consolas; color: blue;">null</span><span style="font-family: Consolas; color: black;">);</span></pre>
<pre style="background: white; border: none; padding: 0in;"><span style="font-family: Consolas; color: black;">};</span></pre>
</div>
<p class="MsoNormal">&nbsp;</p>
<ol>
<li>We grab a buffer from the dataQueue that was populated by the producer</li>
<li>If it&rsquo;s of length zero it means we are done with the stream so we break out of the loop.</li>
<li>Otherwise we schedule an asynchronous write. It is the callback of this method the onw that will return the buffer back to the freeReadBufferQueue.</li>
</ol>
<p class="MsoNormal">As you can see we have both loops working independent from each other and using the Queues to communicate when they have data and when they are done.</p>
<p class="MsoNormal">For the implementation of the queues I&rsquo;m using BlockingCollection. This was released by Microsoft for .Net 4.5. The only downside of this is that it blocks when there is no data in the queue. This can be improved.</p>
<p class="MsoNormal"><strong>So what is the performance for this code?</strong></p>
<p class="MsoNormal">Downloading the same file now takes:</p>
<p class="MsoNormal">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Overall Elapsed:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0:00:06.200</p>
<p class="MsoNormal">We got a <span style="background-color: #00ff00;"><strong>75%</strong> improvement</span> in latency! Also if we go and measure the network utilization in our Proxy we can see that it nicely saturates the network when responding to our request.</p>
<p class="MsoNormal">The code for this article can be found here: <a href="https://github.com/krolth/Http-Proxy-dotnet">https://github.com/krolth/Http-Proxy-dotnet</a></p>
<h2>Notes</h2>
<p class="MsoNormal">If you look at the attached code you will see that we are using preallocating the _freeReadBufferQueue in a static variable. We preallocate 1MB of memory and we use this for all of our requests. This way we ensure that regardless of how many requests we have we will not increase our memory footprint.</p>
<p class="MsoNormal">Another optimization we have is the use of a semaphore in CopyStreamAsync. This is to prevent one big request from hogging all the buffers from _freeReadBufferQueue. In my tests 40 buffers were good enough to return our payload. But if you are using this code I recommend you play around with these settings.</p>
<p class="MsoNormal">The reason I used 4k buffers is that I did not see a lot of improvement with 8k buffer.</p>
<p class="MsoNormal">Here is a table with the latency I saw with different buffer sizes.</p>
<p class="MsoNormal"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/47/37/4544.image002.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-47-37/4544.image002.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/47/37/4544.image002.png" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-47-37/4544.image002.png" alt="" border="0" /></a></p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>ASP.NET Precompilation: Speeding up Orchard cold start</title>
      <link>https://docs.microsoft.com/archive/blogs/shacorn/asp-net-precompilation-speeding-up-orchard-cold-start</link>
      <pubDate>Thu, 13 Nov 2014 16:43:00 GMT</pubDate>
      <dc:creator><![CDATA[Sharad Cornejo Altuzar - MSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/shacorn/2014/11/13/asp-net-precompilation-speeding-up-orchard-cold-start/</guid>
      <description><![CDATA[&nbsp;Orchard is a "Content Management System" that you can use to easily host/customize your...]]></description>
      <content:encoded><![CDATA[<p>&nbsp;<a href="https://www.orchardproject.net/">Orchard</a> is a "Content Management System" that you can use to easily host/customize your content (such as your blog for example). It is built by Microsoft and built on top of ASP.NET MVC. It is one of the Microsoft open source projects so it has a great community and many external modules you can easily add to power your application.</p>
<p>&nbsp;</p>
<p><a href="https://azure.microsoft.com/en-us/services/api-management/">One</a> of the teams I work with in Azure uses it for their Portal Web experience.</p>
<h3>The problem:</h3>
<p>The load time of the website was very slow the first time each page was opened (cold start latency). It would sometimes take upwards of 10 seconds to open a page for the first time. Normally cold start is a very <span style="color: #0000ff;">low</span> priority for a web application. The reason being that a given page might be seen thousands of times so if you have a slow experience only one time of 1000 you will be ok.</p>
<p>Even when you have performance tests for your scenarios you focus on percentiles for your latencies measurements. So 99th percentile will tell you how long it&rsquo;s taking for 99 percent of your users. As you can imagine it&rsquo;s very easy to dismiss the cold start scenario.</p>
<p>In our project this was not the case. Due to many reasons all of our customers would see this at least once for each page they visited (not just the first customer). They would also see it again whenever the server was rebooted which would be at least once a week but probably more than that (since it's hosted in Azure).</p>
<p>Also any new customer would see this whenever they tried the service for the first time (So a very bad first experience).</p>
<p>All of these made it a deal breaker that had to be fixed.</p>
<h3>Analysis</h3>
<p>So I had to figure out what the problem was and how to fix it. I deployed the service and connected to it. Then I started <a href="https://www.microsoft.com/en-us/download/details.aspx?id=28567">Perfview</a> to take a profile while the first page was getting loaded. Here is the result:</p>
<p><strong>ASP.NET Stats View</strong></p>
<p>Statistics Per Request URL</p>
<table border="1" cellpadding="0">
<tbody>
<tr>
<td>
<p align="center"><strong>Method</strong></p>
</td>
<td>
<p align="center"><strong>Path</strong></p>
</td>
<td>
<p align="center"><strong>Query String</strong></p>
</td>
<td>
<p align="center"><strong>Num</strong></p>
</td>
<td>
<p align="center"><strong>Total<br /> MSec</strong></p>
</td>
<td>
<p align="center"><strong>Start of<br /> Max</strong></p>
</td>
<td>
<p align="center"><strong>End of<br /> Max</strong></p>
</td>
</tr>
<tr>
<td>
<p align="center">GET</p>
</td>
<td>
<p align="center">/</p>
</td>
<td>
<p align="center">&nbsp;</p>
</td>
<td>
<p align="center">1</p>
</td>
<td>
<p align="center">24,552</p>
</td>
<td>
<p align="center">2,191.056</p>
</td>
<td>
<p align="center">26,743.336</p>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p><strong>Processes view</strong></p>
<p><strong>Processes that did live for the entire trace.</strong></p>
<table border="1" cellpadding="0">
<tbody>
<tr>
<td width="74">
<p align="center"><strong>Name</strong></p>
</td>
<td width="64">
<p align="center"><strong>CPU<br /> MSec</strong></p>
</td>
<td width="112">
<p align="center"><strong>Ave Procs<br /> Used</strong></p>
</td>
<td width="357">
<p align="center"><strong>Command Line</strong></p>
</td>
</tr>
<tr>
<td width="74">
<p>w3wp</p>
</td>
<td width="64">
<p align="right">1,426</p>
</td>
<td width="112">
<p align="right">0.039</p>
</td>
<td width="357">
<p>d:\windows\system32\inetsrv\w3wp.exe -ap "DefaultAppPool" -v "v4.0" -l "webengine4.dll" -a \\.\pipe\iisipmb30c9525-04d5-42ee-afca-a2530cf3bc4b -h "D:\inetpub\temp\apppools\DefaultAppPool\DefaultAppPool.config" -w "" -m 0</p>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>Processes that did <strong>not</strong> live for the entire trace.</p>
<table border="1" cellpadding="0">
<tbody>
<tr>
<td width="50">
<p align="center"><strong>Name</strong></p>
</td>
<td width="52">
<p align="center"><strong>CPU<br /> MSec</strong></p>
</td>
<td width="64">
<p align="center"><strong>Duration<br /> MSec</strong></p>
</td>
<td width="88">
<p align="center"><strong>Start<br /> MSec</strong></p>
</td>
<td width="351">
<p align="center"><strong>Command Line</strong></p>
</td>
</tr>
<tr>
<td width="50">
<p>csc</p>
</td>
<td width="52">
<p align="right">4,001</p>
</td>
<td width="64">
<p align="right">6,178.415</p>
</td>
<td width="88">
<p align="right">20,013.375</p>
</td>
<td width="351">
<p>"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe" /noconfig /fullpaths @"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\b2554fb2\9f26c9ab\cwyho2o2.cmdline"</p>
</td>
</tr>
<tr>
<td width="50">
<p>csc</p>
</td>
<td width="52">
<p align="right">3,891</p>
</td>
<td width="64">
<p align="right">6,480.819</p>
</td>
<td width="88">
<p align="right">12,201.761</p>
</td>
<td width="351">
<p>"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe" /noconfig /fullpaths @"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\b2554fb2\9f26c9ab\svtkuesz.cmdline"</p>
</td>
</tr>
<tr>
<td width="50">
<p>csc</p>
</td>
<td width="52">
<p align="right">3,429</p>
</td>
<td width="64">
<p align="right">7,121.114</p>
</td>
<td width="88">
<p align="right">4,497.857</p>
</td>
<td width="351">
<p>"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe" /noconfig /fullpaths @"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\b2554fb2\9f26c9ab\0pdpgema.cmdline"</p>
</td>
</tr>
<tr>
<td width="50">
<p>csc</p>
</td>
<td width="52">
<p align="right">562</p>
</td>
<td width="64">
<p align="right">7,891.250</p>
</td>
<td width="88">
<p align="right">28,363.120</p>
</td>
<td width="351">
<p>"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe" /noconfig /fullpaths @"D:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\b2554fb2\9f26c9ab\tn0rpr3e.cmdline"</p>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>Let me translate that for you:</p>
<p>1)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Opening the root of our app took 24.5 seconds!</p>
<p>2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The w3wp process (which is the ASP.NET worker process) only consumed 1.4 seconds of CPU cycles. The rest of the time it was waiting on something</p>
<p>3)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; There is a bunch of <strong>csc</strong> processes running during this time</p>
<p>CSC is the C# <a href="https://msdn.microsoft.com/en-us/library/78f4aasd.aspx">compiler</a>. But why am I seeing it here?</p>
<p>&ldquo;By default, ASP.NET Web pages and code files are compiled dynamically when users first request a resource such as a page from the Web site. After pages and code files have been compiled the first time, the compiled resources are cached. Therefore, subsequent requests to the same page are very efficient.&rdquo;</p>
<p>My first question was why would anyone want to do this? Why would you make your customer pay for this instead of doing it in your developer machine? The answer to that is that this improves the developer experience by a lot! Whenever you are iterating in a website you make many code changes and having to compile after each change is very time consuming. In this mode ASP.NET allows you to go to your website and modify the code (such as the content on your Razor views) and ASP.NET will realize that something changed and will recompile that page for you.</p>
<p>Now I&rsquo;m not 100% sure this is very useful in actual production environments. But I&rsquo;m not an expert on ASP.NET MVC. However the ASP.NET team released a tool that basically lets you precompile your site before you deploy it in case you don&rsquo;t care about this dynamic changes.</p>
<p><a href="https://msdn.microsoft.com/en-us/library/ms227976(v=vs.85).aspx">Here</a> is a guide on how to do it from MSDN.</p>
<h3>Solution</h3>
<p>So we have to use this <strong>aspnet_compiler</strong> tool to fix the problem. However after trying it on our Orchard site I hit some errors such as this:</p>
<p><span style="color: #ff0000;">Error&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The type or namespace name 'Markdown' could not be found (are you missing a using directive or an assembly reference?)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c:\Users\shacorn\AppData\Local\Temp\Temporary ASP.NET Files\orchardlocal\2b51729c\84e739fa\App_Web_ztbavtrn.0.cs&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 29&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Orchard.Web</span></p>
<p><span style="color: #ff0000;">..\Portal\0.0.2063.0\Modules\Orchard.Alias\web.config(35): error ASPCONFIG: Could not load file or assembly 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.</span></p>
<p>Some Orchard forum posts mentioned that this is not supported. Such as <a href="https://orchard.codeplex.com/discussions/238992">this</a> one.</p>
<p>---------------</p>
<p>I talked with one of the Orchard core developers (Sebastien Ros) and he helped me figure out how to make it work with Orchard.</p>
<p>Orchard will dynamically&nbsp;<a href="https://docs.orchardproject.net/Documentation/Orchard-module-loader-and-dynamic-compilation">load</a> modules that are in the Orchard\Modules directories. So to precompile it we need to do a little extra work:</p>
<ol>
<li>Run the precompilation tool against a &ldquo;deploy&rdquo; version of your site. Not from the plain source directory.&nbsp;</li>
<li>When you do &ldquo;deploy&rdquo; from Visual Studio there are some things specific for Orchard that make it necessary to do some other things. In particular due to the way that Orchard loads modules you need to build Orchard modules and pack them in assemblies. This can be done with this command from the Orchard root folder:&nbsp;<br /><span style="color: #0000ff;">build /t:precompiled</span></li>
<li>Note that you need the entire <strong>source code</strong> for Orchard. Not just the redistributable. You can get it from here: <a href="https://www.orchardproject.net/download">https://www.orchardproject.net/download</a>. Make sure you select &ldquo;download the source&rdquo;</li>
<li>Deploy your web application to a directory. For example: <span style="color: #0000ff;">%outputDir%\Web</span></li>
<li>Make sure there are no csproj files under modules or under themes directories. Otherwise they will confuse the tool. Actually there should be no csproj files or cs files. We still will have ASP.NET views (cshtml).<br /><span style="color: #0000ff;">pushd .\Output\Release\Portals.Web\Modules&nbsp; &nbsp; </span><br /><span style="color: #0000ff;"> del *.csproj /s</span></li>
<li>Precompile with a command like this:<br /> <span style="color: #0000ff;">aspnet_compiler -v / -p %outputDir%\Web %outputDir%\Web.Precompiled</span></li>
</ol>
<p>&nbsp;The parameters we are passing to the <strong>aspnet_compiler</strong> are the following:</p>
<ul>
<li>First we are telling the compiler the virtual path to be root or your site (-v /) and the physical path to be %outputDir%\Web. Note that this is the same path we gave as the output path for step (3) above.</li>
<li>Then we pass the output directory for the precompiled version</li>
</ul>
<p>The fact that we are passing root as the virtual path is important because this value will be inserted in the compiled files. So you want them to match the value in your deployed machines.</p>
<h3>How to find the virtual path root for your app?</h3>
<p>The way I found the correct value for this was a little roundabout. As I mentioned before whenever ASP.NET sees a view (cshtml file) it will compile it. The output of this is placed in the folder: &ldquo;Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files&rdquo;.</p>
<p>So I went to the machine where I took the profile and opened one of the generated .compiled files. That showed me something like this:</p>
<p>virtualPath="<span style="background-color: #ffff00;">/Themes</span>/Portals.Themes.Bootstrap/Views/Portals.Web.Authentication/Home/_ProviderInfo.cshtml"</p>
<p>Since <span style="background-color: #ffff00;">Themes</span> is a physical directory I know that the virtualPath should be &ldquo;/&rdquo;. So by passing root (&ldquo;/&rdquo;) I am able to match this.</p>
<p>&nbsp;</p>
<p><strong>Some other things to note about precompilation:</strong></p>
<p>1)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; It will definitely increase your build time. It added 10 minutes in my local machine. So this is something that you probably want to do as part of your deployment script, not something you do every time you build.</p>
<p>2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; It will find errors that you probably did not know you had. Some old views that you need to remove for example.</p>
<p>3)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Precompilation has a known issue with <strong>VirtualPathProvider</strong>. In our case passing (HostingEnvironment.VirtualPathProvider) to the VirtualPathProvider made the issue go away.</p>
<p>&nbsp;</p>
<p>For us the result was dramatic. We were able to get up to 70% performance improvement in latency (99th percentile). The portal feels much faster and the overall experience is much better. Totally recommended :)</p>]]></content:encoded>
    </item>
  </channel>
</rss>