Caching Data in AWS
Caching is an important feature of designing an application in the cloud as caching offers a double function. On one hand, you can think of caching as a temporary database that can automatically expire and delete stale data; on the other hand, caching can be considered as a system that can deliver frequently used data to the user in a much faster manner.
As a simple analogy, consider your refrigerator and the supermarket. Your fridge is basically your local cache, it takes you seconds to get to the fridge and retrieve a yogurt. But it might take you several minutes or even tens of minutes to go buy a yogurt from the supermarket. You can also introduce several layers of cache. For example, your fridge has the lowest capacity but the fastest retrieval rate, whereas the supermarket has the highest capacity but the slower retrieval rate. In some cases, going to a nearby convenience store might make sense instead of going all the way to the supermarket. So the cost of storage of the yogurt is the most expensive in your fridge, whereas the cost of storage at the supermarket is the cheapest. When caching, you are essentially trying to balance the low cost of keeping the yogurt at the supermarket with a higher cost of the fridge, where you want to keep just enough yogurt to feed the family for a few days.
Amazon ElastiCache
ElastiCache is a managed service that helps simplify the deployment of in-memory data stores in AWS. With in-memory data stores, you can perform caching of frequently retrieved responses, maintain session state, and, in some cases, run SQL-like databases that support transaction type queries through scripting.
One of the primary uses for ElastiCache is simple database offloading. Your application is likely to have a high read-to-write ratio, and some requests are possibly made over and over and over again. If all of these common requests are constantly being sent to the back-end database, you might be consuming more power in that database than needed, and it might become very expensive. Instead of constantly retrieving data from the database, you can ensure that frequent responses are cached in an intermediary service that is faster to respond and that can help you reduce the size of the database server. No matter whether your application requires just a simple place to store simple values that it retrieves from the database or whether it requires a scalable, highly available cluster that offers high-performance complex data types, ElastiCache can deliver the right solution for the right purpose.
Memcached
Memcached is a high-performance, distributed, in-memory caching system. The basic design of the Memcached system is meant for storing simple key/value information. The Memcached service differs from the DynamoDB back end in the fact that each key has only one value. Of course, you can nest multiple values into the value of the key, but there is no index to the data because all the data is stored in memory and retrievable with microsecond latency.
Memcached is perfectly suited for simple caching such as offloading of database responses where the key is the query and the value is the response. It is also perfectly suited for storing session information for your web application, where the cookie ID can be used as the key and linked with the session state as the value.
ElastiCache offers an easy way to deploy a Memcached cluster in a single availability zone.
Redis
When a more advanced in-memory database is required, Redis is the solution. Redis supports running an in-memory database in a more classical approach, with a Multi-AZ pair and read replicas in the cluster. It supports more complex datasets and schema-type data, has the ability to be used as a messaging back end, and gives some transactional data access support through Lua scripting.
Amazon DynamoDB Accelerator
The DynamoDB Accelerator (DAX) service is designed to store hot data from a DynamoDB table in memory, which accelerates the read performance of a DynamoDB database up to 10 times. DAX supports millions of requests per second and reduces the latency for each read request from single-digit milliseconds down to microseconds. DAX has a completely transparent read model; essentially, all reads to your table can be redirected to DAX, and no modification is required on the application side.
Amazon CloudFront
CloudFront is a serverless content delivery network that can enhance the user experience of any application running in the AWS cloud, outside the cloud, or on premises. CloudFront provides you with the ability to cache common responses from your HTTP/HTTPS web application by caching the responses to GET, HEAD, and OPTIONS HTTP methods. The data is cached at the AWS edge locations, which are distributed closer to densely populated areas in more than 100 different locations. Figure 4-11 illustrates the AWS regions and edge location distribution across the globe.
Figure 4-11 CloudFront Global Points of Presence
CloudFront also has the ability to establish connections for incoming requests, including PUT, POST, UPDATE, PATCH, and DELETE, thus making it seem as if the application front end is much closer to the user than it actually is. Here is a breakdown of the HTTP methods CloudFront supports:
GET: A read operation that retrieves a document from the web server
HEAD: A read operation that retrieves only the header of the document
OPTIONS: A read request to determine the communication options available on the web server
POST: A write operation that is used to send text-based content to a web server
PUT: A write operation that is used to send a file or data blob to a web server
PATCH: A write operation as an extension to a PUT that enables you to modify an existing file
DELETE: A write operation that deletes a file or some content on a web server
The following settings are supported on a CloudFront distribution:
GET and HEAD: Standard caching for documents and headers. Useful for static websites.
GET, HEAD, and OPTIONS: Adds the ability to cache OPTIONS responses from an origin server.
GET, HEAD, OPTIONS, PUT, PATCH, POST, and DELETE: Terminates all HTTP/HTTPS sessions at the CloudFront edge location and can increase the performance of both read and write requests.
In addition, you can control the time-to-live (TTL) of your cache. By controlling the TTL, you can set a custom way of expiring content when it should be refreshed. CloudFront distributions support the following options for setting TTL:
Min TTL: When forwarding all headers, this is a required setting. Determines the minimum cache lifetime for your CloudFront distribution and determines the shortest interval for CloudFront to check the origin for newer versions of the document.
Max TTL: This optional value defines the longest possible period that objects can stay in the cache. It is used to override any cache-control headers being sent out by the origin.
Default TTL: This optional value works only when no specific TTL is set in the headers coming from the origin. It allows the origin to control its own cache behavior and override the default with cache-control headers.
CloudFront offers the capability to both improve the performance of an application and decrease the cost of content delivery. For example, when delivering content from S3, the transfer costs can add up. With CloudFront, the transfer cost for your data is cheaper per gigabyte. This makes a lot of difference when content that goes viral is hosted on S3. Imagine a video-sharing service where videos tend to go viral and are getting millions of views per day. If each video is 10 MB in size, each million views would carry 10 TB of transfer costs from S3. To achieve the same performance from S3, you can turn on Transfer Acceleration, which increases the delivery speed of content to remote regions. The cost of delivery of the content doubles this way. So with CloudFront you can get initial savings, which can translate to less than 50% of the cost of delivering from S3 with Transfer Acceleration, while also reaping the benefit of having the content cached much closer to the user, who will benefit from the decreased latency of your service. Figure 4-12 illustrates the operation of the CloudFront cache.
Figure 4-12 Basic Operation of the CloudFront Service
Latency is not something to dismiss. Web pages load content somewhat sequentially, and even small increases in back-end performance can add up dramatically. Amazon did a study on latency versus sales performance and discovered that a mere increase of 100 ms in web page load latency would directly influence sales on amazon.com by 1%. Even worse, a study performed by Google found that the traffic to a typical website decreases by 20% if the latency of the web page load is increased by 500 ms. A typical website sequentially loads anywhere between 10 and 100 objects when delivering a web page, and that can translate to a site loading anywhere from a few seconds (less than 3 seconds is considered good) up to tens of seconds for the worst-performing sites. If the latency to request each of those objects is about 100 ms, that alone adds a whole second for each of those 10 objects. Using CloudFront can bring down the request latency times to single-digit or low double-digit milliseconds, thus drastically improving the performance of a web page’s load time even without any site content optimization. It should be noted, though, that optimizing the site content makes the biggest difference; however, optimization can require quite a lot of effort, whereas turning on CloudFront can accelerate a site within minutes.
Another great feature that can help you develop and tune the content delivery is the fact that CloudFront is addressable via the API. This means you can easily control the behavior of the caching environment from within the application. You have complete control over how the headers are forwarded to the origin, you have control over compression, you can modify the responses coming directly out of CloudFront, and you can detect the client type within the cache.
To add some processing power to CloudFront, a distribution can be integrated with Lambda@Edge, which executes predefined functions at the edge location, thus allowing you to include some dynamic responses at the cone of access to your application. The Lambda@Edge execution performance will have the same low latency as the content being delivered from CloudFront and can significantly increase the user experience with your application.
CloudFront Security
CloudFront is secure and resilient to L3 and L4 DDoS attacks when used with AWS Shield Standard. The AWS Shield Advanced service on your CloudFront distribution gives you a 24/7 response team look after your site, allows for custom DDoS mitigation for advanced higher-layer DDoS attacks, and protects you from incurring additional costs associated with the increase in capacity when absorbing a DDoS attack. CloudFront can also be integrated with the AWS Web Application Firewall (WAF), which can help mitigate other types of attacks, such as web address manipulations, injection attacks, and web server vulnerabilities (known and zero-day attacks), and provides the ability to implement different types of rules for allowed patterns, sources, and methods.
To secure data in transit, you can use a TLS endpoint over HTTPS. CloudFront seamlessly integrates with the AWS Certificate Manager (ACM) service, which can automatically provision, renew, and replace an HTTPS certificate on your distribution at no additional cost. This service provides a great benefit to your web application because you never need to worry about renewing, replacing, or paying for an X.509 certificate from a public certificate authority.
You can also use CloudFront to offload all in-transit encryption by sending data to an HTTP origin. When sensitive data is involved, you can use field-level encryption, which only encrypts chosen fields being sent to the server, as with a payment form where the credit card details are encrypted but the rest of the information (such as customer name and address) are sent in clear text to the origin. Field-level encryption uses a set of public and private keys to asymmetrically encrypt and decrypt data across the network and keep the data secure, as illustrated in Figure 4-13.
Figure 4-13 Field-Level Encryption in an AWS CloudFront Distribution
All data being cached by CloudFront is also automatically encrypted at rest through encrypted EBS volumes in the CloudFront distribution servers.
CloudFront also offers the ability to restrict access to your content in three different ways:
Restricting access to your application content with signed URLs or cookies
Restricting access to content based on geolocation
Restricting access to S3 buckets using Origin Access Identity (OAI)
This example shows how to create an OAI and allow access only to a specific S3 bucket through the identity. The command needs two arguments:
CallerReference, which ensures that the request can't be replayed (like a timestamp)
Comment, which essentially gives a friendly name to your distribution
To try this example, run the following:
aws cloudfront create-cloud-front-origin-access-identity \ --cloud-front-origin-access-identity-config \ CallerReference=20190820,Comment=everyonelovesaws
Make sure to capture the OAI ID from the response because you will be using it in your configuration.
Now that you have created the origin access identity, you need to add the identifier of the origin access identity to the bucket policy that you will protect with the origin access identity. The following policy allows only the origin access identity with the ID E37NKUHHPJ30OF to access the everyonelovesaws bucket. You apply this bucket policy to the S3 bucket that you previously made public. Example 4-11 shows a policy that allows access for the origin access identity.
Example 4-11 Bucket Policy for a CloudFront Origin Access Identity
{ "Version": "2008-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E37NKUHHPJ30OF" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::everyonelovesaws/*" } ] }
This policy makes your bucket unavailable until you create the distribution in CloudFront. You can test this by trying to access the bucket through its URL.
To create the CloudFront distribution, you can use the cloudfront.json file shown in Example 4-12 as an input to the AWS CloudFront create-distribution command. In the file you need to define at least the following sections:
CallerReference: A file that prevents replays
DefaultRootObject: The index file to be used in the distribution
Id: The friendly name for the distribution
OriginAccessIdentity: The ID of the origin access identity
DomainName: The FQDN of the S3 bucket or your custom origin
DefaultCacheBehavior: Want to cache
Comment: A comment, which is required but can be left blank
Enabled: A Boolean that can be set to true to enable the distribution or false to disable it
Example 4-12 CloudFront Distribution Configuration File in JSON
{ "CallerReference": "20190820", "Aliases": { "Quantity": 0 }, "DefaultRootObject": "index.html", "Origins": { "Quantity": 1, "Items": [ { "Id": "everyonelovesaws", "DomainName": "everyonelovesaws.s3.amazonaws.com", "S3OriginConfig": { "OriginAccessIdentity": "origin-access-identity/cloudfront/E37NKUHHPJ30OF" } } ] }, "DefaultCacheBehavior": { "TargetOriginId": "everyonelovesaws", "ForwardedValues": { "QueryString": true, "Cookies": { "Forward": "none" } }, "TrustedSigners": { "Enabled": false, "Quantity": 0 }, "ViewerProtocolPolicy": "allow-all", "MinTTL": 0 }, "Comment": "", "Enabled": true }
Save this file to where you are running the CLI command and run the aws cloudfront create-distribution command as follows:
aws cloudfront create-distribution \ --distribution-config file://cloudfront.json
This command returns the complete set of JSON settings from the cloudfront.json file, but the most important thing it returns is the distribution FQDN. Look for the following string in the response from the last command:
"DomainName": "d1iq7pwkt6nlfb.cloudfront.net"
Now you can browse the d1iq7pwkt6nlfb.cloudfront.net FQDN and see that your S3 bucket is accessible only from the CloudFront origin access identity. This FQDN can also be used as a CNAME for your website so you can serve your content with your custom domain name.