

# Integrating AWS Elemental MediaTailor with Amazon CloudFront
<a name="cloudfront-specific-recommendations"></a>

AWS Elemental MediaTailor integrates with Amazon CloudFront to improve content delivery performance and reliability. CloudFront is a content delivery network (CDN) that distributes your content through a worldwide network of data centers called edge locations. When viewers request your content from MediaTailor, CloudFront routes requests to the nearest edge location. This approach reduces latency and improves performance for your viewers.

Integrating MediaTailor with CloudFront provides several key benefits:
+ Reduced latency for viewers accessing personalized content
+ Improved scalability for handling large audience sizes
+ Enhanced reliability through redundant delivery paths
+ Cost optimization through efficient caching strategies
+ Advanced features like multi-Region failover with Media Quality-Aware Resiliency (MQAR)

For comprehensive information about CloudFront features, see the [CloudFront Developer Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html). For information about CloudFront pricing, see [CloudFront Pricing](https://aws.amazon.com/cloudfront/pricing/).

For brevity, we sometimes use "manifests" to refer collectively to multivariant playlists, media playlists, and MPDs.

**Topics**
+ [Basic CloudFront setup](cloudfront-basic-setup.md)
+ [Performance optimization](cloudfront-performance-optimization.md)
+ [Multi-Region resilience](media-quality-resiliency.md)
+ [Monitoring and troubleshooting](monitoring-and-troubleshooting.md)

# Set up basic CloudFront integration with MediaTailor
<a name="cloudfront-basic-setup"></a>

AWS Elemental MediaTailor integration with Amazon CloudFront improves content delivery performance for your viewers. This topic guides you through setting up a basic CloudFront distribution for MediaTailor. With this integration, your viewers can access personalized content through the CloudFront network. You'll also learn how to configure proper caching for different content types.

For information about passing query parameters through CloudFront for authorization and routing, see [MediaTailor manifest query parameters](manifest-query-parameters.md). For advanced routing using dynamic variables, see [MediaTailor domain variables for multiple content sources](variables-domains.md).

## Prerequisites
<a name="cf-basic-prerequisites"></a>

Before configuring CloudFront with MediaTailor, ensure you have the following:
+ An active AWS account with permissions to create and manage CloudFront distributions
+ A configured MediaTailor playback configuration (see [Using AWS Elemental MediaTailor to insert ads](configurations.md))
+ Your content origin server properly set up and accessible
+ Basic understanding of video streaming concepts (HLS/DASH)

## Configuring CloudFront distribution
<a name="cf-basic-configuration"></a>

Follow these steps to create and configure a CloudFront distribution for MediaTailor:

**To create a CloudFront distribution for MediaTailor**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v3/home](https://console.aws.amazon.com/cloudfront/v3/home).

1. Choose **Create Distribution**.

1. For **Origin domain**, enter your MediaTailor endpoint URL (for example, `a1b2c3d4.mediatailor.us-west-2.amazonaws.com`).

1. For **Protocol**, select **HTTPS only**.

1. For **Name**, enter a name that helps you identify this origin (for example, `mediatailor-origin`).

1. Configure the default cache behavior settings:

   1. For **Path pattern**, use the default value (`*`).

   1. For **Compress objects automatically**, select **Yes**.

   1. For **Viewer protocol policy**, select **Redirect HTTP to HTTPS**.

   1. For **Allowed HTTP methods**, select **GET, HEAD**.

   1. For **Cache policy**, select **CachingDisabled**.

   1. For **Origin request policy**, select **AllViewer** to forward all headers for the default behavior.
**Note**  
The default behavior uses AllViewer to safely handle any content that doesn't match specific path patterns. Specific cache behaviors for manifests and segments will be configured separately with appropriate policies.

1. Configure the distribution settings:

   1. For **Price class**, select the option that best matches your audience locations.

   1. For **AWS WAF web ACL**, select an existing web ACL or leave as **Do not enable security protections**.

   1. For **Default root object**, leave empty.

   1. For **Standard logging**, select **On** to enable logging.

1. Choose **Create Distribution**.

## Configuring cache behaviors
<a name="cf-cache-behaviors"></a>

After creating your distribution, you need to configure additional cache behaviors to handle different types of content appropriately. This section covers basic cache behavior setup for CloudFront.

For comprehensive caching optimization including advanced TTL settings, cache key configurations, and performance tuning, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md) in the CDN optimization guide.

### Configuring manifest cache behavior
<a name="cf-manifest-behavior"></a>

Do not cache manifests because they contain personalized content. Follow these steps to configure the cache behavior:

**To configure manifest cache behavior**

1. In the CloudFront console, select your distribution.

1. Choose the **Behaviors** tab.

1. Choose **Create behavior**.

1. For **Path pattern**, enter `*.m3u8` to match HLS multivariant and media playlists.

1. For **Origin**, select your MediaTailor origin.

1. For **Cache policy**, select **CachingDisabled**.

1. For **Origin request policy**, select **AllViewer** to forward all required headers for dynamic content.

1. Choose **Create**.

1. Repeat these steps for DASH manifests using the path pattern `*.mpd` to match MPDs.

This configuration ensures that each viewer receives a personalized manifest with their specific ad content. The CDN doesn't cache these manifests, so each request goes directly to MediaTailor.

### Configuring segment cache behavior
<a name="cf-segment-behavior"></a>

Configure separate cache behaviors for ad segments and content segments to optimize performance and ensure proper CORS handling.

#### Configuring ad segment cache behavior
<a name="cf-ad-segment-behavior"></a>

Ad segments served through the `/tm/*` path pattern require specific configuration to handle CORS properly. Follow these steps:

**To configure ad segment cache behavior**

1. In the CloudFront console, select your distribution.

1. Choose the **Behaviors** tab.

1. Choose **Create behavior**.

1. For **Path pattern**, enter `/tm/*` to match ad segments served by MediaTailor.

1. For **Origin**, select your MediaTailor segments origin (using the `segments.mediatailor.region.amazonaws.com` hostname).

1. For **Cache policy**, select **CachingOptimized**.

1. For **Origin request policy**, select **None**.

1. For **Response headers policy**, select **CORS-with-preflight-and-SecurityHeadersPolicy** to ensure proper CORS headers are included in responses.

1. Choose **Create**.

#### Configuring content segment cache behavior
<a name="cf-content-segment-behavior"></a>

Content segments can use standard caching policies for optimal performance. Configure separate behaviors for different segment formats:

**To configure content segment cache behavior**

1. In the CloudFront console, select your distribution.

1. Choose the **Behaviors** tab.

1. Choose **Create behavior**.

1. For **Path pattern**, enter `*.ts` to match HLS content segments.

1. For **Origin**, select your content origin.

1. For **Cache policy**, select **CachingOptimized**.

1. For **Origin request policy**, select **None**.

1. For **Response headers policy**, select **CORS-with-preflight-and-SecurityHeadersPolicy** to ensure consistent CORS handling across all content types.

1. Choose **Create**.

1. Repeat these steps for other content segment formats using appropriate path patterns:
   + `*.mp4` for MP4 segments
   + `*.m4s` for DASH segments
   + `*.cmfv` and `*.cmfa` for CMAF segments

This configuration ensures that ad segments and content segments are cached appropriately with proper CORS handling. Ad segments use the MediaTailor segments origin with CORS protection, while content segments use your content origin with optimized caching policies.

## Updating MediaTailor configuration
<a name="cf-mediatailor-config"></a>

After setting up your CloudFront distribution, update your MediaTailor configuration to use the CloudFront domain:

**To update your MediaTailor configuration**

1. Open the [MediaTailor console](https://console.aws.amazon.com/mediatailor/home).

1. Select the configuration you want to update.

1. In the **CDN configuration** section, enter your CloudFront distribution domain name (for example, `d1234abcdef.cloudfront.net`) in the **CDN content segment prefix** field.

1. Save your changes.

With this configuration, MediaTailor generates manifests with URLs that point to your CloudFront distribution instead of directly to the origin.

## Testing your integration
<a name="cf-basic-testing"></a>

After configuring your CloudFront distribution and updating your MediaTailor configuration, test the integration:

**To test your CloudFront and MediaTailor integration**

1. Request a manifest through your CloudFront distribution (for example, `https://d1234abcdef.cloudfront.net/v1/master/12345/my-config/index.m3u8`).

1. Verify that the manifest contains segment URLs that point to your CloudFront domain.

1. Play the content through a video player and verify that both content and ads play correctly.

1. Check CloudFront logs to ensure requests are being routed correctly.

## Example configuration
<a name="cf-basic-example"></a>

Here's an example of a CloudFront distribution configuration for MediaTailor with proper cache behaviors:

**Example CloudFront distribution configuration example**  

```
{
  "DefaultCacheBehavior": {
    "TargetOriginId": "mediatailor-origin",
    "ViewerProtocolPolicy": "redirect-to-https",
    "AllowedMethods": {
      "Quantity": 2,
      "Items": ["GET", "HEAD"]
    },
    "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
    "OriginRequestPolicyId": "59781a5b-3903-41f3-afcb-af62929ccde1",
    "Comment": "Default behavior with CachingDisabled and AllViewer"
  },
  "CacheBehaviors": [
    {
      "PathPattern": "*.m3u8",
      "TargetOriginId": "mediatailor-origin",
      "ViewerProtocolPolicy": "redirect-to-https",
      "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
      "OriginRequestPolicyId": "59781a5b-3903-41f3-afcb-af62929ccde1",
      "Comment": "Manifest behavior with CachingDisabled and AllViewer"
    },
    {
      "PathPattern": "*.ts",
      "TargetOriginId": "mediatailor-origin", 
      "ViewerProtocolPolicy": "redirect-to-https",
      "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
      "OriginRequestPolicyId": "88a5eaf4-2fd4-4709-b370-b4c650ea3fcf",
      "Comment": "Segment behavior with CachingOptimized and HostHeaderOnly"
    }
  ]
}
```

This example shows:
+ **Default behavior**: Uses `CachingDisabled` and `AllViewer` to safely handle any content that doesn't match specific path patterns
+ **Manifest behavior (\$1.m3u8)**: Uses `CachingDisabled` and `AllViewer` for dynamic content
+ **Segment behavior (\$1.ts)**: Uses `CachingOptimized` and `CORS-with-preflight-and-SecurityHeadersPolicy`

## Next steps
<a name="cf-basic-next-steps"></a>

After setting up your basic CloudFront integration with MediaTailor, consider these next steps:
+ Optimize performance with additional CloudFront features (see [Optimizing MediaTailor performance with CloudFront features](cloudfront-performance-optimization.md))
+ Implement multi-Region resilience with MQAR (see [Implement multi-Region resilience for MediaTailor with MQAR](media-quality-resiliency.md))
+ Set up monitoring and troubleshooting (see [Monitor and troubleshoot your CloudFront and MediaTailor integration](monitoring-and-troubleshooting.md))

# Optimizing MediaTailor performance with CloudFront features
<a name="cloudfront-performance-optimization"></a>

AWS Elemental MediaTailor performance with Amazon CloudFront can be enhanced through additional features beyond basic configuration. After setting up your basic CloudFront configuration with MediaTailor, you can implement additional features to enhance performance, reliability, and customization options. These optimizations help deliver a better viewing experience. They also reduce costs and origin load.

For performance optimization using dynamic routing and parameter handling, see [MediaTailor dynamic ad variables for ADS requests](variables.md). For query parameter optimization strategies, see [MediaTailor manifest query parameters](manifest-query-parameters.md).

## Reducing origin load with Origin Shield
<a name="origin-shield-integration"></a>

Origin Shield adds a caching layer between CloudFront edge locations and your origin server. This feature is valuable for live streaming and popular VOD content. It helps when many viewers request the same content at the same time.

By consolidating requests from multiple edge locations, Origin Shield reduces the load on MediaTailor and your content origins.

**To enable Origin Shield for your MediaTailor origin**

1. Open the CloudFront console and navigate to your distribution.

1. Select the origin that points to your MediaTailor playback configuration.

1. Under **Origin Shield**, select **Yes**.

1. From the dropdown menu, select the AWS Region that's closest to your MediaTailor endpoint.

1. Save your changes.

For high-traffic events, Origin Shield significantly reduces request load on your origin and improves reliability. For detailed instructions, see [Enabling Origin Shield](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/origin-shield.html#enable-origin-shield) in the CloudFront developer guide.

## Customizing content delivery with CloudFront Functions
<a name="cloudfront-functions-integration"></a>

CloudFront Functions let you run lightweight JavaScript code at the edge to modify viewer requests and responses. You can use these functions for simple customizations like URL modifications, header manipulation, or basic authentication. For MediaTailor workflows, Functions help with tasks that don't require complex processing.

CloudFront Functions provide a lightweight way to customize content delivery at the edge. Here's how to implement them for your MediaTailor integration:

**To implement CloudFront Functions for MediaTailor**

1. In the CloudFront console, navigate to **Functions**.

1. Create a new function and select the appropriate purpose:
   + **URL manipulation** - To modify multivariant playlist, media playlist, and MPD request URLs before they reach MediaTailor
   + **Header manipulation** - To add or modify request headers
   + **Simple authentication** - To validate tokens or query parameters

1. Write your JavaScript function code.

1. Test your function with sample MediaTailor requests.

1. Publish and associate the function with your distribution's cache behavior.

**Example Sample CloudFront Function for URL normalization**  

```
function handler(event) {
    var request = event.request;
    var uri = request.uri;
    
    // Normalize URLs to lowercase to improve cache hit ratio
    if (uri.includes('.m3u8') || uri.includes('.mpd')) {
        request.uri = uri.toLowerCase();
    }
    
    return request;
}
```

For more information and code examples, see [Customize at the edge by using CloudFront Functions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-functions.html) in the CloudFront developer guide.

## Implementing advanced customizations with Lambda@Edge
<a name="lambda-edge-integration"></a>

When you need more complex processing capabilities than CloudFront Functions can provide, use Lambda@Edge. This service lets you run Node.js or Python functions at CloudFront edge locations.

Lambda@Edge functions can perform sophisticated operations like complex authentication, larger response modifications, or third-party API integrations.

For more complex customizations, use Lambda@Edge functions with your MediaTailor and CloudFront integration:

**To implement Lambda@Edge with MediaTailor**

1. Create a Lambda function in the US East (N. Virginia) Region.

1. Write your function code for one of these use cases:
   + **URL manipulation** - To modify multivariant playlist, media playlist, and MPD request URLs before they reach MediaTailor
   + **A/B testing** - To route users to different ad decision servers
   + **Request authentication** - To add authentication headers
   + **Response header modification** - To add CORS headers

1. Publish a version of your function and create a function alias.

1. Associate the function with your CloudFront distribution at the appropriate trigger point (viewer request or viewer response).

**Note**  
When using Lambda@Edge with MediaTailor, avoid using origin-facing triggers (origin request and origin response) if you plan to use Media Quality-Aware Resiliency (MQAR) features, as these are currently incompatible.

For more information and code examples, see [Customize at the edge by using Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html) in the CloudFront developer guide.

## Additional performance optimization tips
<a name="performance-optimization-tips"></a>

Consider these additional optimizations to further improve performance:

Optimize cache hit ratios  
Monitor your cache hit ratio in CloudFront metrics and look for opportunities to improve it:  
+ Standardize URL patterns to improve cache key consistency
+ Use query string whitelisting to include only necessary parameters in the cache key
+ Consider implementing URL normalization with CloudFront Functions

Reduce latency  
Implement these techniques to minimize latency:  
+ Enable Brotli compression for text-based responses
+ Use HTTP/2 or HTTP/3 for improved connection efficiency
+ Consider enabling IPv6 support for modern networks

Cost optimization  
Balance performance with cost efficiency:  
+ Use Origin Shield to reduce redundant origin requests
+ Consider price class selection based on your audience geography
+ Implement aggressive caching for segments to reduce origin traffic

## Next steps
<a name="performance-next-steps"></a>

After optimizing performance with CloudFront features, consider these next steps:
+ Implement multi-Region resilience with MQAR (see [Implement multi-Region resilience for MediaTailor with MQAR](media-quality-resiliency.md))
+ Set up monitoring and troubleshooting (see [Monitor and troubleshoot your CloudFront and MediaTailor integration](monitoring-and-troubleshooting.md))

# Implement multi-Region resilience for MediaTailor with MQAR
<a name="media-quality-resiliency"></a>

AWS Elemental MediaTailor multi-Region resilience is enhanced through Media Quality-Aware Resiliency (MQAR), an advanced Amazon CloudFront feature that helps MediaTailor deliver the best possible streaming experience. It automatically selects the origin with the highest quality score when you have multiple origins in different AWS Regions. This feature is particularly valuable for live streaming where you need uninterrupted service.

## How MQAR works
<a name="mqar-overview"></a>

MQAR enables CloudFront to select the origin with the highest quality score automatically. This ensures that viewers receive the best possible streaming experience. When configured properly, MQAR provides these benefits:
+ Automatic selection of the highest quality origin
+ Seamless failover between AWS Regions during outages
+ Improved viewer experience with minimal interruptions
+ Real-time quality monitoring and adaptation

## Step 1: Verify MQAR requirements
<a name="mqar-requirements"></a>

Before implementing MQAR, verify that your infrastructure meets these requirements. MQAR works by comparing quality scores from multiple origins, so you need identical content available in multiple AWS Regions.
+ Encoders sending aligned ingest streams to all MediaPackage channels using epoch-locked CMAF ingest streamsets
+ Two identical MediaPackage channels in different AWS Regions, with identical origin endpoints
+ CMAF ingest for MediaPackage channels (enabled by default)
+ CloudFront distribution configured to support MQAR
+ MediaTailor configurations for each MediaPackage endpoint

## Step 2: Configure your encoders for MQAR
<a name="mqar-encoder-config"></a>

Your encoders need to produce consistent, synchronized outputs across all Regions for MQAR to work effectively. This consistency allows CloudFront to make accurate quality comparisons between origins.

Configure your MediaLive outputs with these settings:
+ Ensure all video framerates in the CMAF output group are consistent (all fractional or all integer framerates).
+ Avoid transitions between fractional and integer framerates across encoding sessions.
+ Configure output segment sequence numbers so they never go backward across encoding sessions.
+ Use identical encoder output names across all Regions.

For more information about configuring MediaLive for MQAR, see [Working with MQCS](https://docs.aws.amazon.com//medialive/latest/ug/mqcs.html) in the MediaLive user guide.

## Step 3: Configure MediaPackage for MQAR
<a name="mqar-mediapackage-config"></a>

Set up your MediaPackage channels and endpoints with these configurations:

**To configure MediaPackage for MQAR**

1. Create identical channel and endpoint configurations in each AWS Region.

1. Use CMAF as the channel input type.

1. For the primary MediaPackage origin, enable **Force endpoint error** configuration with these settings:
   + Stale multivariant playlists, media playlists, or MPDs
   + Incomplete multivariant playlist, media playlist, or MPD
   + Slate input

1. For back-up MediaPackage origins, do not enable these error configurations to maximize chances of successful failover.

For more information about configuring MediaPackage for MQAR, see [Leveraging media quality scores by using AWS Elemental MediaPackage](https://docs.aws.amazon.com//mediapackage/latest/userguide/mqcs.html) in the MediaPackage user guide.

## Step 4: Configure CloudFront for MQAR
<a name="mqar-cloudfront-config"></a>

In the CloudFront configuration, you enable MQAR and define how it selects between your origins. Create an origin group with the Media quality score option enabled.

**To configure CloudFront for MQAR**

1. Create a CloudFront distribution with origins pointing to your MediaTailor endpoints.

1. Create an origin group that includes these origins.

1. In the origin group settings, enable the **Media quality score** option.

1. Configure failover criteria to include 404 Not Found response codes. You can optionally include other 4xx/5xx codes.

1. Create separate cache behaviors for each channel's path pattern. This prevents mixing scores when the same origin group serves multiple channels.

**Note**  
MQAR is not available when using Lambda@Edge functions in origin-facing triggers (origin request and origin response) that are associated with your distribution's cache behavior.

For more information about configuring CloudFront for MQAR, see [Media quality-aware resiliency](https://docs.aws.amazon.com//AmazonCloudFront/latest/DeveloperGuide/media-quality-score.html) in the CloudFront developer guide.

## Step 5: Configure MediaTailor for MQAR
<a name="mqar-mediatailor-config"></a>

To complete your MQAR setup, configure MediaTailor in each Region to work with your multi-Region architecture. This ensures consistent ad insertion regardless of which origin CloudFront selects.

**To configure MediaTailor for MQAR**

1. Create identical MediaTailor configurations in each Region, pointing to the corresponding MediaPackage endpoints.

1. Configure the CDN content segment prefix to use your CloudFront distribution domain.

1. Ensure that the ad decision server configurations are identical across Regions.

This setup ensures that regardless of which origin CloudFront selects based on quality scores, MediaTailor can continue to personalize ads consistently.

## Step 6: Test your MQAR configuration
<a name="mqar-testing"></a>

After setting up MQAR, test your configuration to ensure it works as expected:

**To test your MQAR configuration**

1. Request content through your CloudFront distribution.

1. Monitor real-time logs to verify that CloudFront is selecting origins based on quality scores.

1. Simulate a failure in your primary AWS Region to test failover behavior.

1. Verify that ad insertion continues to work correctly during failover.

## Next steps
<a name="mqar-next-steps"></a>

After implementing MQAR, consider these next steps:
+ Set up monitoring and troubleshooting for your MQAR configuration (see [Monitor and troubleshoot your CloudFront and MediaTailor integration](monitoring-and-troubleshooting.md))
+ Implement automated deployment using AWS CloudFormation (see [Automate MediaTailor and CDN with CloudFormation](automating-cdn-integration.md))

# Monitor and troubleshoot your CloudFront and MediaTailor integration
<a name="monitoring-and-troubleshooting"></a>

AWS Elemental MediaTailor integration with Amazon CloudFront requires ongoing monitoring and troubleshooting to maintain optimal performance. After implementing your CloudFront and MediaTailor integration, monitor performance and prepare to troubleshoot any issues. The content delivery network (CDN) provides tools to help you understand how your distribution performs and identify potential problems.

## Setting up monitoring for your integration
<a name="cf-monitoring-setup"></a>

Implement these monitoring strategies to track the performance of your CloudFront and MediaTailor integration:

**To set up monitoring for your CloudFront and MediaTailor integration**

1. Enable CloudFront standard logging:

   1. In the CloudFront console, select your distribution.

   1. Choose the **Logs** tab.

   1. Under **Standard logs**, choose **Edit**.

   1. Select **On** and configure an Amazon S3 bucket for log storage.

   1. Choose **Save changes**.

1. Set up CloudFront real-time logs:

   1. In the CloudFront console, select your distribution.

   1. Choose the **Logs** tab.

   1. Under **Real-time logs**, choose **Edit**.

   1. Select **On** and configure an Amazon Kinesis Data Streams or Amazon Data Firehose delivery stream.

   1. Include these fields in your log configuration:
      + `time-to-first-byte` - Response time
      + `sc-status` - HTTP status code
      + `c-ip` - Viewer IP address
      + `cs-uri-stem` - Request URI path
      + `cs-user-agent` - User agent
      + `x-edge-result-type` - Result type (Hit, Miss, Error)

   1. Choose **Save changes**.

1. Create CloudWatch dashboards:

   1. In the CloudWatch console, choose **Dashboards**.

   1. Choose **Create dashboard**.

   1. Add widgets for these CloudFront metrics:
      + Requests
      + BytesDownloaded
      + 4xxErrorRate
      + 5xxErrorRate
      + TotalErrorRate
      + CacheHitRate

1. Set up CloudWatch alarms:

   1. In the CloudWatch console, choose **Alarms**.

   1. Choose **Create alarm**.

   1. Create alarms for these conditions:
      + 5xxErrorRate > 1% for 5 minutes
      + 4xxErrorRate greater than 5% for 5 minutes
      + CacheHitRate less than 80% for 30 minutes

## Monitoring MQAR performance
<a name="mqar-monitoring"></a>

When using MQAR, monitoring helps you understand how CloudFront selects between your origins and whether the quality scores meet expectations. Real-time logs show these decisions as they happen.

**To monitor MQAR performance**

1. Enable real-time logs for your CloudFront distribution.

1. Include these fields in your log configuration:
   + `r-host` - The hostname of the selected origin
   + `sr-reason` - The reason for origin selection
   + `x-edge-mqcs` - The media quality confidence score

1. Set up a log destination in Amazon Kinesis Data Streams or Amazon Data Firehose.

1. Create dashboards or alerts based on these metrics to monitor quality scores and origin selection decisions.

**Example Sample CloudWatch dashboard for MQAR monitoring**  
Create a CloudWatch dashboard with these metrics:  
+ Origin selection counts by Region
+ Average quality scores over time
+ Failover events
+ 4xx and 5xx error rates by origin

For more information about setting up real-time logs, see [Real-time logs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/real-time-logs.html) in the CloudFront developer guide.

## Troubleshooting common issues
<a name="troubleshooting-common-issues"></a>

Issues can arise with your CloudFront and MediaTailor integration even with careful planning. Understanding common problems and solutions helps you resolve issues quickly and minimize viewer impact.

If you encounter issues with your CloudFront and MediaTailor integration, check these common problems and solutions:

Manifest caching issues  
**Symptom:** Stale manifests or ads not updating  
**Solution:** Verify you're using the `CachingDisabled` cache policy for multivariant playlist, media playlist, and MPD paths. Check that your configuration forwards query parameters correctly.

CORS errors  
**Symptom:** Browser console shows CORS errors when accessing content  
**Solution:** Configure a response headers policy with appropriate CORS headers and associate it with your cache behavior.

MQAR not working  
**Symptom:** Origin selection ignores quality scores  
**Solution:** Check that you've enabled the Media quality score option in your origin group settings. Verify you're not using Lambda@Edge origin-facing triggers.

Ad insertion failures  
**Symptom:** Ads not inserting properly  
**Solution:** Verify your MediaTailor configuration points to your CloudFront distribution for content segment prefix. Check that your setup forwards all required headers.

For more complex issues, you can use these troubleshooting approaches:

1. Check CloudFront distribution logs for error patterns

1. Use browser developer tools to inspect network requests

1. Compare manifest content from MediaTailor directly compared to content delivered through CloudFront

1. Test with a simple player that supports detailed logging

For more troubleshooting assistance, see the [Troubleshooting](https://docs.aws.amazon.com//mediatailor/latest/ug/troubleshooting.html) section in the MediaTailor user guide.

## Troubleshooting workflow
<a name="troubleshooting-workflow"></a>

Follow this systematic approach to troubleshoot issues with your CloudFront and MediaTailor integration:

**To troubleshoot CloudFront and MediaTailor integration issues**

1. Identify the specific issue:

   1. Determine if the issue affects all viewers or only some

   1. Identify which content types are affected (manifests, segments, or both)

   1. Note any error messages or symptoms

1. Check CloudFront logs:

   1. Look for error status codes (4xx or 5xx)

   1. Check cache hit/miss patterns

   1. Verify that requests are being routed to the correct origin

1. Verify configuration:

   1. Check cache behaviors for correct path patterns

   1. Verify cache policies are correctly applied

   1. Confirm that origin request policies are forwarding necessary headers

1. Test direct access:

   1. Try accessing content directly from MediaTailor (bypassing CloudFront)

   1. Compare responses between direct access and CloudFront access

1. Implement solution:

   1. Apply the appropriate fix based on your findings

   1. Test to verify the issue is resolved

   1. Document the issue and solution for future reference

## Next steps
<a name="monitoring-next-steps"></a>

After setting up monitoring and troubleshooting for your CloudFront and MediaTailor integration, consider these next steps:
+ Implement automated deployment using AWS CloudFormation (see [Automate MediaTailor and CDN with CloudFormation](automating-cdn-integration.md))
+ Create runbooks for common operational scenarios and troubleshooting procedures
+ Set up automated remediation for common issues