Home > Articles

This chapter is from the book

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

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

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

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)

key_topic_icon.jpg

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.

Pearson IT Certification Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Pearson IT Certification and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Pearson IT Certification products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.pearsonitcertification.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020