Introduction

This article's intention is to explain the main skills measured in this sub-topic of the AZ-204 Certification. Azure CDNs, Azure Front Door, and Redis Cache are the main components that will have their fundamentals explained here alongside a practical example.

This certification is very extensive and this article approaches only the main topics, make sure you know deep down those components before taking the exam. Another great tip is to do exam simulators before the official exam in order to validate your knowledge.

What is the Certification AZ-204 - Developing Solutions for Microsoft Azure?

The AZ-204 - Developing Solutions for Microsoft Azure certification measures designing, building, testing, and maintaining skills of an application and/or service in the Microsoft Azure Cloud environment. It approaches, among others, those components.

Target Audience

Any IT professional willing to improve his knowledge in Microsoft Azure is encouraged to take this certification, it is a great way to measure your skills within trending technologies. But, some groups of professionals are more keen to take maximum advantage of it.

Skills Measured

According to today's date, the skills that are measured in the exam are split as follows.

Benefits of Getting Certified

The main benefit here is having a worldwide recognized certification that proves that you have knowledge of this topic. Among intrinsic and extrinsic benefits, we have.

Main Skills measured by this topic

What are Azure CDNs?

Azure CDN is the Azure service to provide a distributed network of servers to your applications, with Azure CDN you can boost your application's load time, save bandwidth with caching strategies, and speed responsiveness with compressed files. Azure CDNs centralize the requests from your origin into a single point, where it is easier to manage your inbound and outbound traffic with cache strategies, firewall policies, traffic balancing many other features as follows.

Azure CDN Profile

The Azure CDN Profile groups your Azure CDN Endpoints in the same pricing tier, they are not distributed by Azure regions as far as they are a global service. Azure CDN profile has 4 different pricing tiers and can have from 0 to N Endpoints.

Azure CDN Endpoint

CDN Endpoints are where we configure the CDN endpoint that will be exposed as far as the host that is going to be accessed. It has the following main properties.

CDN Endpoint Caching

Azure CDN provides a caching functionality, facilitating the configuration and management of caching requests from our CDN Endpoints. This caching functionality is available in three query string modes.

Caching Purge

Azure CDNs also provide functionality to purge all the cache, this functionality is at the Azure CDN Profile level and you can filter which endpoint and which path is going to have the cache purged.

Caching Rules

You can filter and customize your caching strategy with the caching rules, by default Azure CDNs store the cache for 7 days. Under caching rules we have a default global caching rule with the possibility to add many other custom rules, those rules are formed with conditions that have to be satisfied in order to trigger actions that are going to be executed, and on those actions, we have three types of caching behavior.

What is Azure front door?

Azure Front Door is another Azure Service that, like CDN, centralizes incoming requests into a single endpoint that will distribute those calls to different hosts. An Azure Front Door is formed from Frontends/Domains connected to Backend Pools, and those connections are filtered by the routing rules, it works like a modern CDN, using HTTP/HTTPS Layer 7 and anycast protocol and Azure Front Door main functionalities are the ones as follows.

Caching Policies

Azure Front Door caching policies are almost equal to the Azure CDN caching policies, having some small differences as follows.

What is Redis Cache?

Azure Redis Cache is based on the popular open-source Redis cache. It gives you access to a secure, dedicated Redis cache, managed by Microsoft and accessible from any application within Azure.

Different from the Azure CDNs and Azure Front Door, Azure Redis Cache is not used to cache requests and responses. Azure Redis Cache is used as an in-memory database caching key-value pairs of data. Azure Redis Cache helps your application become more responsive even as the customer load increases. It takes advantage of the low-latency, high-throughput capabilities of the Redis engine. This separate, distributed cache layer allows your data tier to scale independently for more efficient use of the compute resources in your application layer.

Caching Expiration Policies

Azure Redis Caches expiration policies are configured per each request, so we could have an expiration policy different for each cache key. Those expiration policies as the ones that follow for Redis Distributed cache.

Practical Example

Azure CDN

Pre-Requisites

Net Core Web API project created. Here used the Web API Calculator using .Net Core;

In order to have a better demonstration of the functionalities used below, some changes were made in the project in order to work as a Rest API as follows.

[HttpGet]
public IActionResult Index()
{
    return Ok();
}

[HttpPost]
public IActionResult Index([FromQuery] Operation model)
{
    if (model.OperationType == OperationType.Addition)
        model.Result = model.NumberA + model.NumberB;
    return Ok(model);
}

[HttpPost]
public IActionResult CompoundInterest(CompoundInterestModel model)
{
    model.Result = Calculation.CalculateCompoundInterest(model);
    return View(model);
}

[HttpGet]
public IActionResult CompoundInterest()
{
    return View();
}

Create a CDN with Azure CLI

Pre-Requisites

Azure App Service was previously created. Here named NetCoreCalculatorWithCDN and with the following endpoint.

https://netcorecalculatorwithcdn.azurewebsites.net

Setting Variables

$resourceGroup = "cdnCachingResourceGroup"
$cdnProfileName = "sampleCDNProfile"
$cdnEndpointName = "sampleEndpointName"
$cdnSku = "Standard_Microsoft"
$appServiceEndpoint = "netcorecalculatorwithcdn.azurewebsites.net"

Create the CDN Profile.

az cdn profile create --resource-group $resourceGroup --name $cdnProfileName --sku $cdnSku

CDN Profile

Create the CDN endpoint, pointing to your App Service.

az cdn endpoint create --resource-group $resourceGroup --profile-name $cdnProfileName --name $cdnEndpointName --origin $appServiceEndpoint --origin-host-header $appServiceEndpoint

CDN endpoint

Result

Result

CDN Caching

From your CDN endpoint, go to Caching rules and then Configure your CDN Endpoint caching strategy, here we will be caching every unique URL.

CDN Caching

CDN Expiring Cache

From your CDN Endpoint, go to Rules Engine then click on Add Action. Here we will be configuring the cache to expire after 10 seconds.

CDN Expiring

The result from a cached request.

Cached request

Azure Front Door

Pre-Requisites

Azure App Service was previously created. Here named NetCoreCalculatorWithCDN and with the following endpoint

https://netcorecalculatorwithcdn.azurewebsites.net

Creating Azure Front Door

From your Azure Portal, go to Azure Front Door and add a new one. Then on configuration, name your front door.

Front Door

Now, configure your backend pool. Add a backend, and set its name, health probes, and load-balancing configurations.

 Backend pool

HTTPS

Add a routing rule, configuring the cache policy.

Cache policy

Results

Result

Sample

Front Door Caching

From your Azure Front Door go to Front Door Design under Settings and update your routing rule to apply your cache strategy.

Door caching

Send

Front Door Expiring Cache

From your Azure Front Door then go to Front Door Design under Settings and update your routing rule to add the seconds that the cache will live in the Front Door.

Expiring cache

Create a new Rule Engine configuration with a rule to append the cache control in the response header.

Header

Result

GET

Redis Cache with .Net Core Web API

Pre-Requisites

Link to project on GitHub.

Connecting

Update your appsettings.json in order to add your Azure Redis Cache connection string.

{
  "ConnectionStrings": {
    "RedisConnection": "rediscachesample.redis.cache.windows.net:6380,password=+kRlOup8TECk8gNy5dBQv4VG6+KGq3QcbI+MTVxpUwE=,ssl=True,abortConnect=False"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Update your Startup. cs in order to use dependency injection to inject your Redis Cache into your classes.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddStackExchangeRedisCache(options =>
    {
        options.Configuration = Configuration.GetConnectionString("RedisConnection");
    });
}

Extension methods and helpers

In order to facilitate communicating with your Redis Cache, here are some useful extension methods in order to work with complex objects.

public static class RedisCacheHelper  
{  
    public static T GetHelper<T>(this IDistributedCache cache, string cacheKey)  
    {  
        return Deserialize<T>(cache.Get(cacheKey));  
    }  

    public static object GetHelper(this IDistributedCache cache, string cacheKey)  
    {  
        return Deserialize<object>(cache.Get(cacheKey));  
    }  

    public static void SetHelper(this IDistributedCache cache, string cacheKey, object cacheValue)  
    {  
        cache.Set(cacheKey, Serialize(cacheValue));  
    }  

    private static byte[] Serialize(object obj)  
    {  
        if (obj == null)  
        {  
            return null;  
        }  
        BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
        using (MemoryStream objMemoryStream = new MemoryStream())  
        {  
            objBinaryFormatter.Serialize(objMemoryStream, obj);  
            byte[] objDataAsByte = objMemoryStream.ToArray();  
            return objDataAsByte;  
        }  
    }  

    private static T Deserialize<T>(byte[] bytes)  
    {  
        BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
        if (bytes == null)  
            return default(T);  

        using (MemoryStream objMemoryStream = new MemoryStream(bytes))  
        {  
            T result = (T)objBinaryFormatter.Deserialize(objMemoryStream);  
            return result;  
        }  
    }  
}  

Storing data

Example of storing a complex and a list of complex objects.

private IDistributedCache cache;

public HomeController(IDistributedCache cache)
{
    this.cache = cache;
}

public IActionResult SetSimpleComplexObject()
{
    SampleObject sampleObject = new SampleObject
    {
        Country = "Brazil",
        Id = 7,
        Name = "Mané"
    };
    this.cache.SetHelper("test1", sampleObject);

    return RedirectToActionPermanent("Index");
}

public IActionResult SetListComplexObject()
{
    List<SampleObject> lstSampleObject = new List<SampleObject>();
    lstSampleObject.Add(new SampleObject
    {
        Country = "Argentina",
        Id = 1,
        Name = "Maradona"
    });
    lstSampleObject.Add(new SampleObject
    {
        Country = "Portugal",
        Id = 2,
        Name = "Ronaldo"
    });
    lstSampleObject.Add(new SampleObject
    {
        Country = "Puskas",
        Id = 3,
        Name = "Hungary"
    });
    this.cache.SetHelper("test2", lstSampleObject);

    return RedirectToActionPermanent("Index");
}

Retrieving data

Example of retrieving a complex and a list of complex objects.

private IDistributedCache cache;

public HomeController(IDistributedCache cache)
{
    this.cache = cache;
}

public IActionResult Index()
{
    return View(true);
}

public IActionResult GetSimpleComplexObject()
{
    SampleObject sampleObject = new SampleObject();

    sampleObject = this.cache.GetHelper<SampleObject>("test1");
    return View(sampleObject);
}

public IActionResult GetListComplexObject()
{
    List<SampleObject> lstSampleObject = new List<SampleObject>();

    lstSampleObject = this.cache.GetHelper<List<SampleObject>>("test2");

    return View(lstSampleObject);
}

Value

Expiring Policies

Azure Redis Caches provides two different ways to expire your cache, you can set a specific date or set how long the cache, after its creation, is going to live.

cache.Set(cacheKey, Serialize(cacheValue), new DistributedCacheEntryOptions   
{   
    AbsoluteExpirationRelativeToNow = new TimeSpan(1, 9, 0),   
    AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddDays(44))   
});

External References