Azure Web Apps Best Practices

 

 

I want to start off with a disclaimer on this topic that not all practices are the best practice for all scenarios. I have come up with a list, but it’s up to you to pick whichever is the best for you.

Here are some practices that I have gathered working in field:

Choose the closest data center:

Test network latency to Azure Storage in worldwide data centers, determine the best region for your application and users. A closer data center will provide less latency and fast throughput. So if I had to recommend for a customer in my region I would ask them to test the latency using https://www.azurespeed.com/ and decide the right fastest which is nearby.

clip_image002

This tool also give you an option to check on other latency related Media services, CDN, Traffic manager and others as shown below.

clip_image003

 

 

Choose the right size that fits:

What is the right size for my scenario? This is something I have seen with most of the customers and it’s a question difficult to answer. We just throw higher configuration VM’s for any perf related problem. Do not just throw big virtual machines at every problem, Test various configurations under load. Also, don’t have more no of small instances which causes more redundancy. Some scenarios will benefit from more cores where moving data >$ parallel overhead. For example, Video processing, Stateful services (Database Management System (DBMS)). Remember that a scale-up architecture means to increase the size of the virtual machine/Cloud service or Web Apps, while scale out means to increase the number of virtual machines/Cloud Services and Web Apps. So carefully select the right configuration or pricing tiers for your Web Apps. If you aren’t sure then check Load testing capabilities of VSO to check how your app behaves on a specific load and then choose the right size.

Setup your Web apps for auto-scaling to manage unexpected traffic peaks :

There many cloud patterns like unpredictable burst or growing exponential kind of business. For increased performance and throughput for your web apps on Microsoft Azure, you can use the Azure Portal to scale your App Service plan from free mode to Shared, Basic, Standard, or Premium mode. Scaling up on Azure web apps involves two related actions: changing your App Service plan mode to a higher level of service, and configuring certain settings after you have switched to the higher level of service. Higher service tiers like Standard and Premium modes offer greater robustness and flexibility in determining how your resources on Azure are used.

Changing modes and configuring them is easily done in the Scale tab of the management portal. You can scale up or down as required. These changes take only seconds to apply and affect all web apps in your App Service plan. They do not require your code to be changed or your applications to be redeployed.

https://azure.microsoft.com/en-in/documentation/articles/web-sites-scale/

App Service Environment:

Consider an App Service Environment which provides a fully isolated and dedicated environment for securely running all of your apps including Web Apps, Mobile Apps, API Apps and Logic Apps. An App Service Environment is always created inside of a regional virtual network. This enables apps to securely connect to other endpoints accessible only inside of a virtual network, including endpoints connected via Site-to-Site and ExpressRoute connections. It also enables an App Service Environment to be secured behind upstream appliances, firewalls and network SaaS providers. Apps running in an App Service Environment also have even more scaling options, including the ability to run on up to fifty (50) compute instances and the new P4 compute resource.

https://azure.microsoft.com/en-us/documentation/articles/app-service-app-service-environment-intro/

Load test your website:

Load test your web apps using different scale configurations (combination of Instance size and number of instances) to understand the right scale configuration under regular load. Various tools like Visual Studio, Apache Jmeter can be used to perform load tests. Learn more https://www.visualstudio.com/en-us/get-started/test/load-test-your-app-vs

Run some Web Analytic tools:

Consider using Web Analytic tools like App insights, New relic, Google Analytics or WebTrends to identify the traffic patterns and the average requests per second for your website.

https://azure.microsoft.com/en-in/documentation/articles/app-insights-get-started/

Take advantage of Deployment Slots for testing inproduction using Staged sites:

Windows Azure Web Apps supports staged publishing that enables you to deploy updates to your staging version of the website and test it out in a production environment before updating your customer-facing website. See Staged Publishing on Windows Azure Web Apps to learn more https://azure.microsoft.com/en-us/documentation/articles/web-sites-staged-publishing/

Take advantage of Traffic Routing:

You can redirect minimal traffic for your web apps to the staging and rest to the production web app so that you don’t see any surprises when you fully move staging to production.Ramp-Up testing (aka Canary Deployment) – test your prototype by slowly increasing number of visitors seeing new feature. You can start with 5%, monitor performance/errors for a while and add another 5%. Do this until you find some critical errors or until you reach 100% (then you’ll have your new base).

https://glamcoder.ru/azure-websites-testing-in-production-to-win-en/

Enable diagnostic logging:

Azure Web Apps has built-in diagnostics to help you with debugging your application. There are two types of diagnostics:

  • Site diagnostics: It allows you to enable detailed error logging, failed request Tracing and web server logging.
  • Application diagnostics: It allows you to capture information produced by a web application.

See How to enable diagnostic logging for Windows Azure websites to learn more https://azure.microsoft.com/en-us/documentation/articles/web-sites-enable-diagnostic-log/

Remote Debugging: We can now do remote debugging in Visual studio of the Web Apps to find issues in the application.

https://azure.microsoft.com/en-us/blog/introduction-to-remote-debugging-on-azure-web-sites/

Enable monitoring:

Azure Web apps supports monitoring functionality via the Monitor management page. You can setup alerts for various metrics like CPU Time, HTTP Client Errors, HTTP Server errors etc. to continuously monitor your website. See How to monitor your Windows Azure website to learn more https://azure.microsoft.com/en-us/documentation/articles/web-sites-monitor/

 

Write Secure Web Applications:

Finding security issues and fixing it in production can be costly. So plan for security best practices for your application early in your development cycle. Azure Web apps complies with the key industry standards for security and reliability to provide our customers a secure platform but if your application has security vulnerabilities then it can make your architecture susceptible to an attack.

Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. By using Key Vault, you can encrypt keys and secrets (such as authentication keys, storage account keys, data encryption keys, .PFX files, and passwords) by using keys that are protected by hardware security modules (HSMs). Key Vault streamlines the key management process and enables you to maintain control of keys that access and encrypt your data. Developers can create keys for development and testing in minutes, and then seamlessly migrate them to production keys. Security administrators can grant (and revoke) permission to keys, as needed.

https://azure.microsoft.com/en-in/documentation/articles/key-vault-get-started/

To build a secure solution on Azure Apps, you must follow secure coding practices when building your application to withstand an attack. See How to write secure code to learn more https://msdn.microsoft.com/en-us/security/aa570401.aspx

You can use Azure’s native network security features to help protect information assets, check the white paper

https://download.microsoft.com/download/C/A/3/CA3FC5C0-ECE0-4F87-BF4B-D74064A00846/AzureNetworkSecurity_v3_Feb2015.pdf

 

Decouple your application logic: Decouple the application logic between web apps and web jobs in your application. You can run programs or scripts in WebJobs in your App Service web app in three ways: on demand, continuously, or on a schedule. There is no additional cost to use WebJobs.

https://azure.microsoft.com/en-in/documentation/articles/web-sites-create-web-jobs/

Automate Infrastructure:

There are a lot of operations involved outside the cloud solution which includes development, deployment and various other operations to successfully maintain your Web apps. Automating these operations can make it easier to manage the shipping cycle for your application. All Azure Web apps features can be accessed using WAWS REST API making it easier to automate. You can also use ARM to have template based deployment and Role based Access for resources.

Some of the key operations for managing your website:

Deployments to the Web apps:

  • You can use various deployment strategies like Web deploy, GIT, FTP etc. that can be easily automated to push out the content to your website(s) by building tools using Windows Azure SDK for the deployment tool of your preference.
  • ARM (Azure Resource Manager): Applications are typically made up of many components – maybe a web app, database, database server, storage, and 3rd party services. You do not see these components as separate entities, instead you see them as related and interdependent parts of a single entity. You want to deploy, manage, and monitor them as a group. Azure Resource Manager enables you to work with the resources in your application as a group. You can deploy, update or delete all of the resources for your application in a single, coordinated operation. You use a template for deployment and that template can work for different environments such as testing, staging and production. You can clarify billing for your organization by viewing the rolled-up costs for the entire group. Azure Resource Manager natively integrates access control into the management platform so you can specify which actions a user in your organization can take for a resource group.

https://azure.microsoft.com/en-in/documentation/articles/resource-group-overview/

https://azure.microsoft.com/en-in/documentation/articles/resource-group-authoring-templates/

Stateless web servers behind a smart load balancer:

Stateless web tier means you don't store any application data in the web server memory or file system. Keeping your web tier stateless enables you to both provide a better customer experience and save money:

  • If the web tier is stateless and it sits behind a load balancer, you can quickly respond to changes in application traffic by dynamically adding or removing servers. In the cloud environment where you only pay for server resources for as long as you actually use them, that ability to respond to changes in demand can translate into huge savings.
  • A stateless web tier is architecturally much simpler to scale out the application. That too enables you to respond to scaling needs more quickly, and spend less money on development and testing in the process.

Caching:

Use Caching and but try to avoid session state (or if you can’t avoid it, use distributed cache rather than a database). It's often not practical in a real-world cloud app to avoid storing some form of state for a user session, but some approaches impact performance and scalability more than others. If you have to store state, the best solution is to keep the amount of state small and store it in cookies. If that isn't feasible, the next best solution is to use ASP.NET session state with a provider for distributed, in-memory cache. Azure offers the following caching services: Azure Redis Cache and Azure Managed Cache. Azure Redis cache is based on the popular open source Redis Cache and is the first choice for most caching scenarios. It gives you access to a secure, dedicated Redis cache, managed by Microsoft. A cache created using Azure Redis Cache is accessible from any application within Microsoft Azure.

https://azure.microsoft.com/en-in/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/

Use a CDN to edge-cache static file assets (images, scripts)

The Azure Content Delivery Network (CDN) caches Azure blobs and static content used by cloud services at strategically placed locations to provide maximum bandwidth for delivering content to users

The CDN offers developers a global solution for delivering high-bandwidth content by caching the content at physical nodes across the world. For a current list of CDN node locations, see Azure Content Delivery Network (CDN) POP Locations.

The benefits of using the CDN to cache Azure data include:

  • Better performance and user experience for end users who are far from a content source, and are using applications where many "internet trips" are required to load content.
  • Large distributed scale to better handle instantaneous high load, like at the start of a product launch event.

Learn more https://azure.microsoft.com/en-in/documentation/articles/cdn-serve-content-from-cdn-in-your-web-application/

 

 

 

Use Blobs for large frequently changing static content

Identify static assets in your application (e.g. images, CSS, and JavaScript files) and use blob storage for that instead of including them with your application package file. To reduce load on the application, use blob storage to serve larger static content (> 100 kB). Consider using loading such static content when you are updating these resources frequently in the application.

 

Use .NET 4.5’s async support to avoid blocking calls:

.NET 4.5 enhanced the C# and VB programming languages in order to make it much simpler to handle tasks asynchronously. The benefit of asynchronous programming is not just for parallel processing situations such as when you want to kick off multiple web service calls simultaneously. It also enables your web server to perform more efficiently and reliable under high load conditions. A web server only has a limited number of threads available, and under high load conditions when all of the threads are in use, incoming requests have to wait until threads are freed up. If your application code doesn't handle tasks like database queries and web service calls asynchronously, many threads are unnecessarily tied up while the server is waiting for an I/O response. This limits the amount of traffic the server can handle under high load conditions. With asynchronous programming, threads that are waiting for a web service or database to return data are freed up to service new requests until the data the is received. In a busy web server, hundreds or thousands of requests can then be processed promptly which would otherwise be waiting for threads to be freed up.

  • Async support in ASP.NET 4.5

In ASP.NET 4.5, support for asynchronous programming has been added not just to the language but also to the MVC, Web Forms, and Web API frameworks. For example, an ASP.NET MVC controller action method receives data from a web request and passes the data to a view which then creates the HTML to be sent to the browser. Frequently the action method needs to get data from a database or web service in order to display it in a web page or to save data entered in a web page.

  • Async support in Entity Framework 6

As part of async support in 4.5 we shipped async support for web service calls, sockets, and file system I/O, but the most common pattern for web applications is to hit a database, and our data libraries didn’t support async. Now Entity Framework 6 adds async support for database access.

Use Bundling and minification:

Consider feature like bundling that makes it easy to “bundle” or “combine” multiple CSS and JavaScript files into fewer HTTP requests. This causes the browser to request a lot fewer files and in turn reduces the time it takes to fetch them.

ASP.NET has also a feature that makes it easy to reduce or “minify” the download size of the content as well. This is a process that removes whitespace, comments and other unneeded characters from both CSS and JavaScript. The result is smaller files, which will download and load in a browser faster.

So, these strategies will kind of reduce the amount of data going out of the Azure Web Server for which you will be billed. Any ways incoming data to Azure is free.

Design the architecture to be resilient to failures:

Although, Azure Web Apps offers a high SLA . For business continuity, it is important to understand the risk of service failures when using a cloud solution and identifying ways to reduce the impact during such an event.

Here are some must-do solutions to mitigate in such situations:

  • Have an automated backup-and-restore strategy for your content by building your own tools with Windows Azure SDK or in Azure Portal or using third-party services like Cloud Cellar
  • Avoid single-instance roles; this configuration does not meet the requirements for the Azure SLA. During a node failure or upgrade event, a single-instance role is taken offline. Limit their use to low-priority “maintenance” tasks. Setup redundant copies of your website on at least 2 datacenters and Load balance incoming traffic between these datacenters.
  • Setup automatic failover capabilities when a service goes down in a datacenter using a Global traffic manager
  • Setup Content delivery network (CDN) service along with your Web Apps to boost performance by caching content and provide a high availability of your Web Apps.
  • Remove dependency of any tightly coupled components/services you use with your Web Apps if possible.

If you must have a dependent component, replication strategy can help make your architecture more robust.

  • Design a risk-mitigation strategy before moving to the cloud to mitigate unexpected outages
  • Create a staged environment and simulate failure scenarios by stopping your sites to evaluate how your website performs under failure

Implement appropriate SQL retry policies:

Plan for all service calls (SQL Database, storage, and so on) to handle transient failure conditions and connectivity loss. Data access code should leverage a policy-driven retry mechanism to compensate for transient connection faults. The retry mechanism should detect temporary connection faults, reconnect to the target SQL Database, and reissue the command.

https://msdn.microsoft.com/en-us/library/hh675232.aspx

Optimize data transfer objects (DTOs): DTO’s for serialization and network transmission. Given the highly distributed nature of Azure applications, scalability is bounded by how efficiently individual components of the system can communicate over the network. Any data passed over the network for communication or storage should implement JSON text serialization or a more efficient binary format with appropriate hints to minimize the amount of metadata transferred over the network (such as shorter field names “on the wire”).

Use Cloud Patterns effectively

There are around twenty-four design patterns focusing on Performance, Security and Transactions and so on. Check out the complete list here: https://msdn.microsoft.com/en-us/library/dn568099.aspx

Set Billing Alerts:

This is a common concern from most of my customers, they are not sure of what is consumed when and how billing shoots up. You can use the Azure Billing Alert Service to create customized billing alerts that help you monitor and manage billing activity for your Azure accounts. So better you set billing alert for the specific needs and Microsoft Azure will notify you when that alert rule executes. Also you can check the new pricing calculator which is pretty good, which helps you to get an estimate of the overall services that you are using. You can also drill down to the Resource group level to find the cost that is associated with Azure.

https://azure.microsoft.com/en-in/documentation/articles/azure-billing-set-up-alerts/

Hope you get some good pointers to improve your current practices. 

Thanks for stopping by.

Cheers,

Goutham