Maximizing Performance: A Comprehensive Guide to Caching, Content Delivery, and Best Practices in Azure

Susheel Shinde | Dec 14th 2023

Maximizing Performance: A Comprehensive Guide to Caching, Content Delivery, and Best Practices in Azure

In today’s fast-paced digital landscape, optimizing performance is paramount for delivering a seamless user experience. This blog post explores the integration of caching and content delivery within solutions, leveraging Azure services for enhanced efficiency. We’ll delve into Azure Cache for Redis, CDN platforms, and introduce Azure Front Door. Additionally, we’ll discuss common use cases, best practices, and provide valuable resources for implementation.

Understanding Azure Cache for Redis

Redis is typically used as a cache to improve the performance and scalability of systems that rely heavily on backend data stores. Performance is improved by temporarily copying frequently accessed data to fast storage located close to the application.

Data in Redis is stored in nodes and clusters.

  • Nodes are a space in Redis where your data is stored.
  • Clusters are sets of three or more nodes your dataset is split across. Clusters are useful because your operations will continue if a node fails or is unable to communicate to the rest of the cluster.

 

Redis Data Types and Operations

Redis supports a variety of data types, all oriented around binary safe strings. This means that you can use any binary sequence for a value, from a string like “i-love-rocky-road” to the contents of an image file. An empty string is also a valid value.

Here’s a list of the most common data types:

  • Binary-safe strings (most common)
  • Lists of strings
  • Unordered sets of strings
  • Hashes
  • Sorted sets of strings
  • Maps of strings

Each data value is associated to a key that can be used to look up the value from the cache. Redis works best with smaller values (100k or less), so consider chopping up bigger data into multiple keys. Storing larger values is possible (up to 500 MB), but increases network latency and can cause caching and out-of-memory issues if the cache isn’t configured to expire old values.

Figure 1, Redis data types (Microsoft documentation)

Redis keys are also binary safe strings. Here are some guidelines for choosing keys:

  • Avoid long keys. They take up more memory and require longer lookup times because they have to be compared byte-by-byte. If you want to use a binary blob as the key, generate a unique hash and use that as the key instead. The maximum size of a key is 512 MB, but you should never use a key that size.
  • Use keys that can identify the data. For example, “sport:football;date:2008-02-02” would be a better key than “fb:8-2-2”. The former is more readable and the extra size is negligible. Find the balance between size and readability.
  • Use a convention. A good one is “object:id”, as in “sport:football”.

Redis supports a set of known commands. A command is typically issued as COMMAND parameter1 parameter2 parameter3.

Here are some common commands that you can use:

Command                    Description

Ping                                      Pings the server. Returns “PONG”.

set [key] [value]                 Sets a key/value in the cache. Returns “OK” on success.

get [key]                              Gets a value from the cache.

exists [key]                         Returns ‘1’ if the key exists in the cache, ‘0’ if it doesn’t.

type [key]                           Returns the type associated to the value for the given key.

incr [key]                             Increments the given value associated with key by ‘1’. The value must be an integer or double value. This returns the new value.

incrby [key] [amount]       Increments the given value associated with key by the specified amount. The value must be an integer or double value. This returns the new value.

del [key]                              Deletes the value associated with the key.

Flushdb                               Deletes all keys and values in the database.

 

Azure Cache for Redis

Azure Cache for Redis is a fully managed, highly scalable, and secure caching service that enables applications to achieve high throughput and low-latency access to data. Leveraging an in-memory data store is an ideal solution for enhancing the performance of your applications.

Azure Cache for Redis is based on the popular software Redis. With Azure Cache for Redis, the fast storage commonly associated with Redis is located in-memory with Azure Cache for Redis instead of being loaded from disk by a database.

Application performance is improved by taking advantage of the low-latency, high-throughput performance of the Redis engine. Azure Cache for Redis gives you access to a secure, dedicated Azure Cache for Redis, managed by Microsoft, hosted within Azure, and accessible to any application within or outside of Azure.

There are three pricing tiers available for an Azure Cache for Redis.

  • Basic: Basic cache ideal for development/testing. Is limited to a single server, 53 GB of memory, and 20,000 connections. There is no SLA for this service tier.
  • Standard: Production cache, which supports replication and includes an 99.99% SLA. It supports two servers (primary/secondary), and has the same memory/connection limits as the Basic tier.
  • Premium: Enterprise tier, which builds on the Standard tier and includes persistence, clustering, and scale-out cache support. This is the highest performing tier with up to 530 GB of memory and 40,000 simultaneous connections.

You can control the amount of cache memory available on each tier—this is selected by choosing a cache level from C0-C6 for Basic/Standard and P0-P4 for Premium.

Azure Cache for Redis usage

Azure Cache for Redis can also be used as an in-memory data structure store, a distributed non-relational database, and a message broker.

Figure 2, Azure cache usage (Microsoft documentation)

Because a database can be large, loading an entire database into a cache is not a recommended approach. It is common to use the cache-aside pattern to load data items into the cache only as needed. When the system makes changes to the back-end data, it can at that time also update the cache, which is distributed with other clients. Additionally, the system can set an expiration on data items, or use an eviction policy to cause data updates to be reloaded into the cache.

Accessing a Redis Cache from a Client

To connect to an Azure Cache for Redis instance, you’ll need several pieces of information. Clients need the host name, port, and an access key for the cache. You can retrieve this information in the Azure portal through the Settings > Access Keys page.

  • The host name is the public internet address of your cache, which was created by using the name of the cache—for example, sportsresults.redis.cache.windows.net.
  • The access key acts as a password for your cache. There are two keys created: primary and secondary. You can use either key, but two are provided in case you need to change the primary key. You can switch all of your clients to the secondary key, and regenerate the primary key. This would block any applications using the original primary key. Microsoft recommends periodically regenerating the keys, much as you would your personal passwords.

Note: Your access keys should be considered confidential information, so treat them as you would a password. Anyone who has an access key can perform any operation on your cache!

Connecting to a Redis cache from a client involves using a Redis client library. Popular libraries include StackExchange.Redis for .NET, redis-py for Python, and Jedis for Java. Establishing a connection, performing operations, and handling errors are essential considerations.

Developing for Storage on CDNs

Content Delivery Networks (CDNs) distribute content across a network of servers, enhancing performance and reducing latency. When developing for CDN storage:

  • Leverage CDN-compatible storage services (Azure Blob Storage, Azure Table Storage).
  • Implement proper cache headers and versioning for assets.
  • Optimize images and other static resources for faster delivery.

 

CDN Usage

CDNs are typically used to deliver static content, such as images, style sheets, documents, client-side scripts, and HTML pages. The major advantages of using a CDN are lower latency and faster delivery of content to users—regardless of their geographical location in relation to the datacenter where the application is hosted. CDNs can also help to reduce the load on a web application, because the application does not have to service requests for the content that is hosted in the CDN.

Figure 3, CDN usage (Microsoft documentation)

Azure CDN Platform and Usage

In Azure, the Azure Content Delivery Network (Azure CDN) is a global CDN solution for delivering high-bandwidth content that is hosted in Azure or in any other location. By using Azure CDN, you can cache publicly available objects loaded from Azure Blob Storage, a web application, a virtual machine, or any publicly accessible web server. Azure CDN can also accelerate dynamic content, which cannot be cached, by taking advantage of various network optimizations by using CDN POPs. An example is using route optimization to bypass Border Gateway Protocol (BGP).

Azure CDN (Content Delivery Network) enhances the performance of web applications by caching content closer to users. Azure CDN supports various delivery scenarios, including web applications, media streaming, and large file distribution. Integration is seamless with Azure services like Blob Storage and Web Apps.

Azure CDN accelerates content delivery, providing a global network of edge servers. Key features and usage considerations:

  • Endpoint creation and configuration.
  • CDN profiles and rules for customizing behavior.
  • HTTPS support and custom domains for secure delivery.
  • Integration with Azure services for seamless content deployment.

 

Azure CDN Usage

  1. A user (Example User) requests a file (also called an asset) by using a URL with a special domain name, such as endpoint name.azureedge.net. This name can be an endpoint hostname or a custom domain. The Domain Name System (DNS) routes the request to the best-performing POP location, which is usually the POP that is geographically closest to the user.
  2. If no Edge servers in the POP have the file in their cache, the POP requests the file from the origin server. The origin server can be an Azure web app, Azure cloud service, Azure storage account, or any publicly accessible web server.
  3. The origin server returns the file to an Edge server in the POP.
  4. An Edge server in the POP caches the file and returns the file to the original requestor (Example User). The file remains cached on the Edge server in the POP until the Time to Live (TTL) specified by its HTTP headers expires. If the origin server didn’t specify a TTL, the default TTL is seven days.
  5. Additional users can then request the same file by using the same URL that the original requestor (Example User) used, which can also be directed to the same POP.
  6. If the TTL for the file hasn’t expired, the POP Edge server returns the file directly from the cache. This process results in a faster, more responsive user experience.

Figure 4, Azure CDN usage (Microsoft documentation)

Cache Expiration in Azure CDN

Effective cache expiration is crucial for ensuring users receive the latest content. Azure CDN provides multiple mechanisms for cache control, including Time-to-Live (TTL) settings, purging content, and using cache headers. Understanding these options enables you to strike the right balance between performance and content freshness.

Efficient cache expiration ensures users receive the latest content. Consider the following approaches:

  • Set appropriate cache-control headers for content.
  • Leverage cache purging or invalidation mechanisms.
  • Combine cache expiration with versioning for dynamic content.

 

What is Azure Front Door?

Azure Front Door is Microsoft’s modern cloud Content Delivery Network (CDN) that provides fast, reliable, and secure access between your users and your applications’ static and dynamic web content across the globe. Azure Front Door delivers your content using Microsoft’s global edge network with hundreds of global and local points of presence (PoPs) distributed around the world close to both your enterprise and consumer end users.

Comparison with Azure CDN Services

Azure Front Door and Azure CDN are both Azure services that offer global content delivery with intelligent routing and caching capabilities at the application layer. Both services can be used to optimize and accelerate your applications by providing a globally distributed network of points of presence (POP) close to your users. Both services also offer a variety of features to help you secure your applications from malicious attacks and to help you monitor your application’s health and performance.

Common Use Cases

 

  • Accelerating Dynamic Content

Azure Cache for Redis is ideal for accelerating dynamic content, such as database query results or computed data. By caching frequently accessed data in Redis, you reduce the load on backend services, resulting in faster response times.

  • Global Content Delivery

Azure CDN excels in delivering content globally. With a vast network of edge locations, it minimizes latency by serving content from the nearest edge server. This is especially beneficial for applications with a diverse user base. Azure Front Door helps in Global load balancing for dynamic content and has WAF integration for enhanced security. 

Top 5 Best Practices

 

  • Understand Your Data Access Patterns: Tailor your caching strategy to your application’s specific data access patterns. Analyze which data is accessed frequently and benefits the most from caching.
  • Set Appropriate TTL Values: Balance cache freshness with performance by setting Time-to-Live values based on the volatility of your data. Shorter TTLs ensure fresher content but may increase cache misses.
  • Implement a Cache Invalidation Strategy: Use cache invalidation techniques to refresh the cache when underlying data changes. This prevents users from accessing outdated content.
  • Monitor and Optimize: Regularly monitor cache performance, usage, and hit rates. Use Azure Monitor and Azure CDN analytics to identify bottlenecks and optimize configurations accordingly.
  • Use a Multi-Tiered Caching Approach: Combine Azure Cache for Redis with Azure CDN for a multi-tiered caching strategy. Use Redis for dynamic data and CDN for static content, maximizing performance across the entire application.

 

By leveraging Azure Cache for Redis and Azure CDN, you can significantly enhance your application’s performance and deliver a seamless experience to users worldwide. Understanding the intricacies of Redis data types, operations, and CDN configuration empowers you to implement effective caching strategies and follow best practices for optimal results. For more in-depth guidance and the latest updates, explore the provided resources.

Remember, performance optimization is an ongoing process. Regularly revisit your caching strategies, monitor performance metrics, and adapt to the evolving needs of your application and user base.

References:

  • Azure Redis Cache Overview (https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-overview)
  • Azure CDN Overview (https://learn.microsoft.com/en-us/azure/cdn/cdn-overview)
  • Comparison between Azure Front Door and Azure CDN Services (https://learn.microsoft.com/en-us/azure/frontdoor/front-door-cdn-comparison)
No Comments

Sorry, the comment form is closed at this time.