

# Using a CDN to optimize MediaTailor ad personalization and content delivery
<a name="integrating-cdn"></a>

AWS Elemental MediaTailor works effectively as a standalone service, but integrating it with a content delivery network (CDN), such as Amazon CloudFront or other third-party CDNs, can significantly enhance your streaming workflows. A CDN integration is particularly valuable when you need to serve content to a large, geographically distributed audience or when you want to ensure consistent ad delivery across different AWS Regions.

Without a CDN, your viewers connect directly to MediaTailor for personalized manifests and ad segments, which can lead to increased latency, especially for viewers located far from the AWS Region where your MediaTailor configuration is deployed. Additionally, during high-traffic events, direct connections to MediaTailor might experience increased load, potentially affecting performance.

For more information about MediaTailor concepts and workflows, see [What is AWS Elemental MediaTailor?](what-is.md).

When integrating a CDN with MediaTailor, it's important to configure proper CORS (Cross-Origin Resource Sharing) handling to prevent issues that which can cause playback failures in web-based players. Proper CORS configuration is essential for both ad segments and content segments. While ad segments are more susceptible to CORS issues, applying consistent CORS handling across all segment types ensures the most reliable playback experience. For detailed guidance on configuring CDN routing behaviors with proper CORS handling, see [Production-ready CloudFront configuration for MediaTailor](cf-comprehensive-configuration.md).

CDN integration also enables advanced parameter passing and dynamic routing capabilities. For information about passing query parameters through CDNs for authorization and routing, see [MediaTailor manifest query parameters](manifest-query-parameters.md). For dynamic ad server and origin routing using configuration aliases, see [MediaTailor dynamic ad variables for ADS requests](variables.md).

Placing a CDN between your viewers and MediaTailor provides the following benefits:
+ Reduce latency by serving content from edge locations closer to viewers
+ Improve scalability by distributing load across the CDN's global infrastructure
+ Enhance reliability through redundant delivery paths
+ Optimize costs by reducing origin traffic
+ Implement advanced features like Media Quality-Aware Routing (MQAR) for improved streaming quality

**Topics**
+ [CDN selection](cdn-selection-guidance.md)
+ [Plan CDN integration](planning-cdn-integration.md)
+ [Set up CDN integration](cdn-configuration.md)
+ [Ad insertion with CDN](ssai-cdn-workflow.md)
+ [Channel assembly with CDN](ca-cdn-wflw.md)
+ [MediaPackage CDN integration](mediapackage-integration.md)
+ [CloudFront integration](cloudfront-specific-recommendations.md)
+ [Third-party CDN setup](cdn-provider-specific.md)
+ [CDN performance optimization](cdn-optimization.md)
+ [CDN monitoring](cdn-monitoring.md)
+ [CDN integration testing](cdn-integration-testing.md)
+ [Troubleshoot CDN integration](cdn-troubleshooting.md)
+ [CDN integration log analysis reference](cdn-log-error-reference.md)
+ [CloudFormation automation](automating-cdn-integration.md)
+ [Production CloudFront configuration](cf-comprehensive-configuration.md)
+ [Get CDN integration support](cdn-get-help.md)

# Select the right CDN for your needs
<a name="cdn-selection-guidance"></a>

Choosing the right content delivery network (CDN) provider is an important decision that can impact your content delivery performance, cost, and viewer experience with AWS Elemental MediaTailor. Consider these factors when selecting a CDN for your MediaTailor implementation:

**Geographic coverage**  
Choose a CDN with strong presence in regions where your audience is located. Different CDN providers have varying strengths in different geographic regions.

**Integration with AWS services**  
Amazon CloudFront offers the tightest integration with MediaTailor and other AWS services, which can simplify setup and management. Third-party CDNs might offer other advantages like specialized video delivery features or stronger presence in specific regions.

**Video-specific features**  
Look for CDNs that offer features specifically designed for video delivery, such as adaptive bitrate optimization, video compression, and analytics focused on viewer experience.

**Cost structure**  
Compare pricing models across providers, considering factors like traffic volume, geographic distribution, and feature requirements. Some CDNs offer volume discounts or committed use discounts that might align with your usage patterns.

**Support for advanced features**  
Verify that your chosen CDN supports the features you need, such as token authentication, geo-restriction, request collapsing, and proper header forwarding.

For more information about specific CDN providers and their integration with MediaTailor, see the following resources.
+ [CloudFront integration](cloudfront-specific-recommendations.md) for Amazon CloudFront
+ [Third-party CDN setup](cdn-provider-specific.md) for third-party CDN providers

The following topics provide comprehensive guidance on configuring MediaTailor with a CDN for optimal performance.

# Plan your CDN integration for AWS Elemental MediaTailor
<a name="planning-cdn-integration"></a>

You can improve the viewer experience and reduce latency with a CDN integration for AWS Elemental MediaTailor. When you implement a content delivery network (CDN), you can deliver content from locations that are closer to your viewers. This ensures faster load times, better scalability, and consistent ad delivery across different geographic regions.

You need proper planning before implementing a CDN with AWS Elemental MediaTailor. This section guides you through the key planning areas. You address these areas before beginning the actual configuration. These steps help you create an optimal viewing experience for your audience.

After you complete your planning, see [Integrating a CDN with MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/cdn-integration.html) for step-by-step implementation instructions.

For information about MediaTailor quotas that may affect your CDN planning, see [Quotas in AWS Elemental MediaTailor](quotas.md). For information about CloudFront quotas, see [Quotas](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) in the CloudFront Developer Guide.

Before you start planning, understand how MediaTailor interacts with a CDN:

1. The viewers request content through your CDN instead of directly from MediaTailor

1. The CDN forwards manifest requests to MediaTailor for personalization.

1. The CDN caches and serves content segments and ad segments from edge locations.

This architecture reduces load on MediaTailor while you ensure viewers receive personalized ads with minimal latency.

Understanding the manifest terminology helps you configure your CDN correctly. Different streaming protocols use specific manifest structures that affect how you set up the caching and routing:
+ *HLS manifests* - When you work with HLS streams, you handle:
  + *Multivariant playlist*: Configure your CDN to route these top-level manifests to MediaTailor for personalization.
  + *Media playlist*: Set appropriate caching rules for these manifests that contain links to content segments.
+ *DASH manifests* - When you work with DASH streams, you handle:
  + *MPD (Media Presentation Description)*: Configure your CDN to handle these manifests according to your personalization requirements.

The CDN planning process involves these key steps, each focused on a specific task:
+ [Estimate traffic requirements for CDN and MediaTailor integrations](estimate-traffic.md): Calculate your expected viewer concurrency and the bandwidth requirements.
+ [Configure optimization strategies for CDN and MediaTailor integrations](optimize-cdn-config.md): Configure your CDN for optimal content delivery and ad personalization.
+ [Customize planning for CDN and MediaTailor integrations](plan-for-workflow.md): Adjust your CDN strategy based on your specific MediaTailor workflow.
+ [Set up monitoring and scaling for CDN and MediaTailor integrations](setup-monitoring.md): Implement monitoring and scaling strategies for reliable performance.
+ [Optimize costs for CDN and MediaTailor integrations](optimize-costs.md): Balance the performance with the cost efficiency.
+ [Test your implementation for CDN and MediaTailor integrations](test-implementation.md): Thoroughly test your CDN integration before production deployment.

# Estimate traffic requirements for CDN and MediaTailor integrations
<a name="estimate-traffic"></a>

To accurately size your content delivery network (CDN) integration with AWS Elemental MediaTailor:

1. Calculate your expected viewer concurrency using historical data or similar events. Plan for additional capacity beyond your baseline to handle unexpected spikes. For current scaling recommendations, consult with your AWS account team. You can also see [Quotas in AWS Elemental MediaTailor](quotas.md).

1. Identify peak traffic patterns and potential spikes in your content schedule. Consider factors like:
   + Live sports events or season premieres
   + Marketing campaigns or promotional events
   + Time zone differences for global audiences
   + Holiday or seasonal viewing patterns

1. Determine your bandwidth requirements by multiplying viewer counts by stream bitrates. Work with your CDN provider to calculate appropriate capacity. Base this calculation on your specific content bitrates and expected audience size. Add overhead for ad segments and manifest requests as your provider recommends.

1. Work with your CDN provider to ensure sufficient edge capacity in your target regions.

Ensure your ad insertion capacity meets viewer demand by taking these specific actions:

1. Check your current ad insertion requests quota in the [Service Quotas console](https://console.aws.amazon.com/servicequotas/home/services/mediatailor/quotas). Review the current service limits to understand how many concurrent viewers your configuration can support.

1. For high-traffic events, request an increased quota through the [Service Quotas console](https://console.aws.amazon.com/servicequotas/home/services/mediatailor/quotas).

1. If you expect more than 500,000 concurrent viewers, then contact [AWS Support](https://aws.amazon.com/premiumsupport/) at least 2 weeks before your event. This allows AWS to ensure sufficient capacity for your ad personalization needs.

For more information about implementing capacity planning in your workflow, see [Using prefetch scheduling](https://docs.aws.amazon.com/mediatailor/latest/ug/prefetch.html) to optimize ad delivery for high-traffic events.

# Configure optimization strategies for CDN and MediaTailor integrations
<a name="optimize-cdn-config"></a>

When you complete your traffic estimation, configure your content delivery network (CDN) to optimize content delivery and ad personalization with AWS Elemental MediaTailor. These optimizations help ensure smooth playback while maintaining targeted advertising.

Implement these specific CDN optimizations that follow:

1. Configure origin shield capabilities in your CDN to reduce load on MediaTailor and improve caching efficiency. Origin shield acts as an intermediary caching layer that:
   + Consolidate multiple viewer requests into a single origin request
   + Reduce the number of redundant requests to MediaTailor
   + Improve the response times for the cached content

   For implementation details on setting up origin shield with CloudFront, see [Using Origin Shield](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/origin-shield.html) in the CloudFront Developer Guide.

1. Set appropriate Time To Live (TTL) values for different content types. TTL determines how long the CDN caches content. After this time, the CDN requests a fresh copy from the origin:
   + Manifests: 
     + 0 seconds for ad insertion
     + 5-10 seconds for channel assembly

     In ad insertion, MediaTailor provides manifests with ads personalized to the viewer. If a playlist or MPD is cached and served to the wrong playback device, the device could encounter playback or tracking issues.
   + Content segments: 24 or more hours (these rarely change and you can cache them aggressively to reduce origin load)
   + Ad segments: 24 or more hours (ad content is typically reused across viewers and you can cache it for extended periods)

   For comprehensive TTL recommendations and caching optimization strategies across all MediaTailor workflows, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

   For detailed instructions on configuring cache behaviors in CloudFront, see [Cache Behavior Settings](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesCacheBehavior) in the CloudFront Developer Guide.

1. Deploy CDN edge nodes close to your viewer populations. Work with your CDN provider to:
   + Identify optimal edge node locations based on viewer demographics
   + Ensure sufficient capacity in each region
   + Monitor edge performance and adjust as needed

   For implementation guidance, see [CloudFront edge locations](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html) to identify available edge locations for your audience regions.

1. For global audiences, consider implementing a multi-CDN strategy. This approach:
   + Uses multiple CDN providers to improve reliability
   + Routes viewers to the best-performing CDN for their location
   + Provides failover options during CDN outages
   + Can optimize costs by leveraging different pricing models

   For implementation details, see [Multi-CDN strategies](https://aws.amazon.com/blogs/networking-and-content-delivery/multi-cdn-strategies/) on the AWS Networking & Content Delivery Blog.

# Customize planning for CDN and MediaTailor integrations
<a name="plan-for-workflow"></a>

Different AWS Elemental MediaTailor workflows have unique requirements that affect content delivery network (CDN) planning. For workflow-specific guidance, see [Working with configurations](https://docs.aws.amazon.com/mediatailor/latest/ug/configurations.html).

Adjust your capacity plan based on your specific MediaTailor workflow:

## For MediaTailor ad insertion workflows
<a name="plan-ad-insertion"></a>

1. Configure your CDN to handle personalized manifests with zero caching. This ensures each viewer receives unique, targeted ads. The ads are based on their profile and viewing context.

1. Size your ad decision server (ADS) to handle peak request volumes. For guidance on ADS configuration, see [Ad insertion with MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/ad-insertion.html). Consider:
   + Response time requirements for your use case
   + Expected concurrent viewer capacity
   + Redundancy and failover requirements
   + Geographic distribution needs

1. Implement request collapsing at the CDN level to handle synchronized ad break requests. Request collapsing combines multiple identical requests into a single origin request. This is crucial during:
   + Live sports events when many viewers hit ad breaks simultaneously
   + Popular TV show premieres with synchronized commercial breaks
   + Breaking news events that attract sudden viewer spikes

   For implementation details, see [Origin failover](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html) to configure request handling during peak loads.

## For MediaTailor channel assembly workflows
<a name="plan-channel-assembly"></a>

1. Calculate capacity requirements based on the number of channels and their bitrates. For guidance on channel assembly capacity planning, see [Channel assembly in MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/channel-assembly.html). Consider:
   + Total number of channels
   + Bitrate requirements per channel
   + Expected concurrent viewer load
   + Geographic distribution needs

1. Configure your CDN to handle predictable traffic patterns based on published schedules. Channel assembly typically has more predictable patterns than ad insertion because:
   + Programming schedules are known in advance
   + Viewer behavior follows established patterns
   + Content doesn't change dynamically per viewer

1. Ensure your origin has sufficient bandwidth to maintain consistent channel output. Implement:
   + Redundant origin servers for high-availability channels
   + Automated failover between primary and backup origins
   + Monitoring to detect origin performance issues

   For implementation guidance, see [Setting up origin redundancy](https://docs.aws.amazon.com/mediapackage/latest/ug/cloudfront-origin-failover.html) to create a resilient origin infrastructure.

## For combined MediaTailor workflows
<a name="plan-combined-workflow"></a>

1. Size your infrastructure to handle the combined traffic patterns of both services. For guidance on combined workflows, see [Using AWS Elemental MediaTailor to insert ads](configurations.md). Consider:
   + Channel assembly baseline requirements
   + Ad insertion overhead requirements
   + Peak traffic patterns
   + Redundancy needs

1. Configure separate CDN behaviors for linear content delivery and dynamic ad insertion. This separation allows you to:
   + Optimize caching policies for each content type independently
   + Route requests to appropriate origins based on content type
   + Monitor performance metrics separately for each workflow

1. Set up proper routing between edge and origin CDNs to maintain optimal performance. Consider using:
   + Different origin paths for content segments (/content/\$1) and ad segments (/ads/\$1)
   + Separate cache behaviors for manifests and segments
   + Geographic routing to optimize latency for different regions

   For implementation details, see [Configuring cache behaviors](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesCacheBehavior) to set up path-based routing and caching rules.

# Set up monitoring and scaling for CDN and MediaTailor integrations
<a name="setup-monitoring"></a>

Effective monitoring and scaling strategies are crucial for maintaining optimal performance and viewer experience with your AWS Elemental MediaTailor content delivery network (CDN) integration. Implement these approaches to ensure your CDN integration performs reliably at scale.

Implement these monitoring and scaling strategies that follow:

1. Configure monitoring for these key metrics. For guidance on appropriate target values, see [Monitoring MediaTailor with Amazon CloudWatch](https://docs.aws.amazon.com/mediatailor/latest/ug/monitoring-cloudwatch-metrics.html) and consult your CDN provider's best practices:
   + CDN cache hit ratios (establish baseline metrics and targets based on your content type and delivery patterns)
   + Origin request volumes (monitor patterns during normal operation to establish baselines for anomaly detection)
   + Error rates by error type (define thresholds based on your service level objectives and MediaTailor best practices)
   + Response times (set appropriate latency targets based on your viewer experience requirements and geographic distribution)

   For detailed implementation instructions, see [Creating CloudWatch dashboards](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html) to visualize your MediaTailor and CDN metrics together.

1. Set up alerts for unexpected traffic patterns or performance degradation. Configure thresholds based on your baseline metrics and service level objectives. For guidance on setting up alerts, see [Creating Amazon CloudWatch alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html). Consider monitoring:
   + Significant deviations from baseline cache hit ratios (typically alert when falling under 85-90%)
   + Sudden increases in origin request volume (alert on 30% or greater increase from baseline)
   + Error rate spikes exceeding your defined thresholds (typically 1-2% for 4xx errors, 0.5% for 5xx errors)
   + Response time degradation beyond acceptable levels (typically >500ms for manifests, >200ms for segments)

   For implementation examples, see [CloudWatch concepts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html) for creating effective monitoring dashboards and alerts.

1. Create scaling plans for predictable high-traffic events. Your plans should include these key elements:
   + Pre-event capacity increases (24-48 hours before event start)
   + Gradual viewer ramp-up schedules (typically 10-20% of expected audience per 5-minute interval)
   + Regional capacity distribution based on audience (allocate capacity proportionally to expected regional viewership)
   + Post-event scaling procedures (maintain peak capacity for 30-60 minutes after event conclusion)

   For implementation guidance on scaling for high-traffic events, see [Setting up a resilient end-to-end live workflow](https://aws.amazon.com/blogs/media/part-1-how-to-set-up-a-resilient-end-to-end-live-workflow/) on the AWS Media Blog.

1. Implement failover and redundancy measures for critical streams, including:
   + Multi-region CDN deployments (at least two regions for critical content)
   + Backup origin servers (configured with automated health checks every 30 seconds)
   + Automated failover triggers based on health checks (typically after 2-3 failed checks)
   + Recovery procedures for different failure scenarios (documented with specific response time targets)

   For detailed implementation steps, see [Optimizing high availability with CloudFront origin failover](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html).

# Optimize costs for CDN and MediaTailor integrations
<a name="optimize-costs"></a>

Content delivery network (CDN) costs can vary significantly based on traffic patterns, geographic distribution, and feature usage with AWS Elemental MediaTailor. For current pricing information, see [CloudFront pricing](https://aws.amazon.com/cloudfront/pricing/). You can also consult your CDN provider's documentation.

Balance the performance with the cost efficiency by using these strategies:

1. Analyze your CDN traffic patterns to select the most cost-effective pricing tier. Review the following factors with your CDN provider:
   + Data transfer volumes by region and time period
   + Request patterns for manifests and segments
   + Geographic distribution requirements
   + Peak versus average usage patterns

   For help with cost analysis, use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate your CloudFront costs based on your specific usage patterns.

1. For predictable workloads, evaluate reserved capacity agreements with your CDN provider. These agreements can offer benefits such as:
   + Discounted rates for committed usage volumes
   + Predictable monthly costs for budgeting
   + Priority support and capacity allocation

   Consult with your CDN provider to determine if reserved capacity is appropriate for your usage patterns. For CloudFront, see [CloudFront premium features](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-premium-features.html). This provides information about reserved capacity options.

1. Optimize egress costs by balancing traffic between MediaTailor and your CDN provider. Strategies include:
   + Maximize cache hit ratios to reduce origin requests
   + Use origin shield to consolidate requests
   + Implement compression to reduce data transfer volumes
   + Choose CDN regions that align with AWS Region pricing

   For implementation guidance on compression, see [Serving compressed files](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html) in the CloudFront Developer Guide.

1. Implement appropriate caching strategies for different content types to reduce origin requests. For guidance on cache optimization, see [Improving cache hit ratios](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cache-hit-ratio.html). Focus on:
   + Content segments (you can cache these for extended periods)
   + Ad segments (typically reused across viewers)
   + Static assets like player files and images

   Improved cache hit ratios significantly reduce origin costs. Work with your CDN provider to optimize cache configurations for your specific content patterns. For detailed implementation steps, see [Configuring cache behaviors](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ConfiguringCaching.html).

# Test your implementation for CDN and MediaTailor integrations
<a name="test-implementation"></a>

Ensure reliable viewer experiences by thoroughly testing your AWS Elemental MediaTailor content delivery network (CDN) integration before production deployment. Proper testing helps identify and resolve issues before they impact your audience. For guidance on testing methodologies, see [Testing CloudFront distributions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-testing.html). You can also consult your CDN provider's testing documentation.

Follow these testing steps that validate your CDN integration:

1. Create a test environment that mirrors your production configuration. Include:
   + Identical CDN settings and cache behaviors
   + Include representative content with various bitrates and formats
   + Configure test ad decision server with sample ad responses
   + Set up monitoring and alerting configurations

   For step-by-step implementation guidance, see [Creating a staging distribution](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-testing.html) in the CloudFront Developer Guide.

1. Conduct load testing to verify your capacity estimates. For guidance on load testing, see [Monitoring MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/ug/monitoring-service.html). Test scenarios should include:
   + Gradual viewer count increases (typically 10-20% of expected peak every 5 minutes)
   + Sudden traffic spikes based on your expected peak loads (simulate 50% of peak audience joining within 60 seconds)
   + Extended peak load periods (maintain peak load for at least 30-60 minutes)
   + Geographic distribution matching your audience (distribute test traffic according to expected viewer locations)

   Validate that response times remain under target thresholds. Typically, this means less than 500ms for manifests and less than 200ms for segments. Error rates should stay under 1%. For implementation details on load testing tools and methodologies, see [Load testing with CloudFront](https://aws.amazon.com/blogs/networking-and-content-delivery/load-testing-with-cloudfront/) on the AWS Networking & Content Delivery Blog.

1. Test failover scenarios to ensure reliability. Simulate:
   + Origin server failures (complete outage and partial degradation scenarios)
   + CDN edge location outages (test with traffic routing to backup locations)
   + Ad decision server unavailability (test with 5-10 second timeouts)
   + Network connectivity issues (simulate packet loss and latency increases)

   Work with your CDN provider to establish appropriate failover response time targets for your use case. Typically, this means less than 3 seconds for failover completion. For implementation guidance on failover testing, see [Origin failover](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html) in the CloudFront Developer Guide.

1. For major events, implement gradual ramp-up strategies based on [AWS load testing guidelines](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/load-testing.html):
   + Stagger start times for different audience segments. For example, allow premium subscribers first with 15-minute intervals between audience groups.
   + Use pre-warming techniques to gradually increase load. Pre-warming involves:
     + Populate CDN caches with popular content 2-4 hours before the event
     + Gradually increase synthetic traffic to 20-30% of expected peak to warm up systems
     + Test all components under realistic load conditions with actual content
   + Monitor system performance throughout the ramp-up period, tracking:
     + Cache hit ratios and response times (target >90% hit ratio, <500ms response)
     + Error rates and origin load (maintain error rates <1%, origin CPU <70%)
     + Ad personalization success rates (target >98% successful personalization)
     + Viewer experience metrics (target <2 second startup time, <0.5% rebuffering)
   + Have a contingency plan for unexpected traffic surges. Your plan should include these essential components:
     + Emergency capacity scaling procedures with documented steps to increase capacity by 50-100% within 15 minutes
     + Backup CDN activation protocols with ability to shift 20-50% of traffic to secondary CDN
     + Simplified ad insertion fallback to reduce targeting parameters from 10 or more to 3-5 essential ones
     + Communication plans for stakeholders with pre-defined notification templates and contact lists

   After completing your testing, proceed to [Implementing your CDN integration](https://docs.aws.amazon.com/mediatailor/latest/ug/cdn-integration.html) for production deployment steps.

# Troubleshoot common issues for CDN and MediaTailor integrations
<a name="troubleshooting-cdn"></a>

Address common content delivery network (CDN) integration challenges with AWS Elemental MediaTailor before they impact your viewers. This section helps you identify and resolve typical issues that occur during CDN integration with AWS Elemental MediaTailor.

For comprehensive troubleshooting guidance, see [Troubleshooting MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/troubleshooting.html) and [Troubleshooting CloudFront distributions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/troubleshooting.html).

## Resolving MediaTailor manifest delivery problems
<a name="manifest-issues"></a>

If viewers experience playback issues or see incorrect ads, check these common manifest-related problems:
+ **Incorrect caching settings**: If your CDN caches personalized manifests, viewers may see ads intended for other users.

  Solution: Configure your CDN with a cache TTL of 0 for manifest requests to MediaTailor.
+ **Origin request failures**: If your CDN can't reach MediaTailor, then manifest requests will fail.

  Solution: Check network connectivity between your CDN and MediaTailor. Verify your CDN properly forwards the correct headers.
+ **Session parameter issues**: Missing or incorrect session parameters can cause personalization failures.

  Solution: Ensure that your player is correctly appending all required session parameters to the manifest requests.

## Fixing MediaTailor segment delivery problems
<a name="segment-issues"></a>

If content or ad segments aren't loading properly, investigate these common issues:
+ **Segment path rewriting**: Incorrect CDN configuration may rewrite segment URLs improperly.

  Solution: Verify your CDN correctly handles segment URLs. Ensure it doesn't modify paths in a way that breaks references.
+ **CORS configuration**: Missing or incorrect CORS headers can prevent browsers from loading segments.

  Solution: Configure your CDN to pass the appropriate CORS headers for segment requests.
+ **Cache miss storms**: During high-traffic events, multiple cache misses can overwhelm origin servers.

  Solution: Implement request collapsing and origin shield capabilities to reduce origin load during traffic spikes.

## Addressing MediaTailor CDN performance problems
<a name="performance-issues"></a>

If viewers experience buffering or slow loading, check these performance-related issues:
+ **Low cache hit ratio**: If your CDN frequently requests content from the origin, then performance will suffer.

  Solution: Analyze the cache hit ratios by content type and adjust the TTL settings to improve caching efficiency.
+ **Geographic distribution**: Viewers distant from CDN edge locations may experience increased latency.

  Solution: Review your CDN edge location distribution. Add capacity in regions with high viewer concentrations.
+ **Origin capacity limitations**: If your origin servers are overloaded, then response times will increase.

  Solution: Implement origin request limiting. You can also increase origin capacity or improve caching to reduce origin load.

For additional troubleshooting assistance, see [Troubleshooting MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/troubleshooting.html) or contact AWS Support. For implementation guidance on resolving common CDN issues, see [Debugging your content delivery network](https://aws.amazon.com/blogs/media/debugging-your-content-delivery-network/) on the AWS Media Blog.

# Set up CDN integration with MediaTailor
<a name="cdn-configuration"></a>

This section provides guidance on integrating AWS Elemental MediaTailor with a content delivery network (CDN). 

Effective CDN integration with MediaTailor is essential for delivering high-quality streaming experiences with personalized ads at scale. This guide walks you through the complete process of setting up, configuring, and optimizing your CDN integration.

For additional information, see the following links:
+ For information about passing query parameters through CDNs for authorization and ad targeting, see [MediaTailor manifest query parameters](manifest-query-parameters.md). 
+ For advanced routing using dynamic variables and configuration aliases, see [MediaTailor dynamic ad variables for ADS requests](variables.md).
+ For information about creating MediaTailor configurations, see [Using AWS Elemental MediaTailor to insert ads](configurations.md). 
+ For information about creating a CloudFront distribution, see [Creating a distribution](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html) in the CloudFront Developer Guide.

To ensure clarity in this guide, the following terminology is used to describe different types of manifests:
+ **HLS manifests**:
  + *Multivariant playlist*: The top-level manifest that contains links to media playlists
  + *Media playlist*: The second-level manifest with links to content segments
+ **DASH manifests**:
  + *MPD (Media Presentation Description)*: The standard term for DASH manifests

Integrating MediaTailor with a CDN provides the following benefits:
+ Reduced latency for viewers
+ Improved scalability for high-traffic events
+ Enhanced reliability through redundant delivery paths
+ Optimized costs by reducing origin traffic
+ Better protection against DDoS attacks

## CDN integration components and requirements
<a name="cdn-integration-components"></a>

A successful CDN integration with MediaTailor involves configuring the following key components:

**CDN routing behaviors**  
Rules that determine how different types of requests (manifests, content segments, ad segments) are routed through your CDN.

**CDN mapping in MediaTailor**  
Configuration in MediaTailor that ensures manifests reference your CDN domain instead of directly referencing origin servers.

**Security settings**  
Configurations that protect your content and infrastructure, including transport security, access control, and monitoring.

**Testing and validation**  
Procedures to verify that your CDN integration is working correctly before deploying to production.

## Prerequisites for CDN integration
<a name="prerequisites"></a>

Before configuring your CDN integration, ensure you have the following:

1. A MediaTailor configuration with the following settings:
   + Your content origin as the **Content source**
   + Your ADS as the **Ad decision server**

   You need the origin and ADS URLs in the CDN integration steps as well.

1. Access to your CDN's configuration interface

1. Understanding of your CDN's specific terminology for behaviors, rules, and cache settings

1. Knowledge of your content structure, including file extensions used for segments (such as .ts, .mp4, or .m4s)

## CDN integration setup steps
<a name="cdn-integration-workflow"></a>

The process of integrating MediaTailor with a CDN follows these high-level steps:

1. **Configure CDN routing behaviors** - Set up your CDN to route different types of requests appropriately.

1. **Configure CDN mapping in MediaTailor** - Update your MediaTailor configuration to use your CDN domain names.

1. **Implement security best practices** - Configure security settings to protect your content and infrastructure.

1. **Test your integration** - Verify that your CDN integration is working correctly.

## Required headers for MediaTailor CDN integration
<a name="cdn-required-headers"></a>

For MediaTailor to function correctly with your CDN, you must configure your CDN to forward specific HTTP headers. These headers are essential for proper functionality including compression, device detection, ad personalization, and geo-targeting.

Configure your CDN to forward the following headers to MediaTailor:

**`Accept-Encoding`**  
**Purpose**: Required for compression functionality  
**Details**: This header tells MediaTailor which compression methods the client supports. MediaTailor uses this information to compress manifests when possible, reducing bandwidth usage and improving performance. Legacy devices that don't support compression won't send this header, and MediaTailor will return uncompressed manifests.

**`User-Agent`**  
**Purpose**: Required for device detection and ad personalization  
**Details**: MediaTailor analyzes the User-Agent header to identify the client device type, browser, and capabilities. This information is used for ad targeting, device-specific optimizations, and ensuring compatibility with different playback clients.

**`Host`**  
**Purpose**: Required for proper request routing  
**Details**: The `Host` header ensures that requests are routed to the correct MediaTailor endpoint. This is particularly important in multi-tenant environments and when using custom domain configurations.  
Many CDNs, including Amazon CloudFront, do not forward the `Host` header by default. For CloudFront users: See [Configuring cache behaviors](cloudfront-basic-setup.md#cf-cache-behaviors) for configuration instructions.

**`X-Forwarded-For`**  
**Purpose**: Required for client IP detection and geo-targeting  
**Details**: This header preserves the original client IP address when requests pass through your CDN. MediaTailor uses this information for geographic ad targeting, analytics, and compliance with regional content restrictions.

**Important**  
All four headers are required for full MediaTailor functionality. Missing any of these headers can result in reduced functionality, including:  
Inability to compress manifests (missing Accept-Encoding)
Poor ad targeting and device compatibility issues (missing User-Agent)
Request routing failures (missing Host)
Inaccurate geo-targeting and analytics (missing X-Forwarded-For)

For CDN-specific configuration instructions, see the routing behaviors and caching sections that reference this header list.

The following topics provide detailed instructions for each aspect of CDN integration.

**Topics**
+ [CDN integration components and requirements](#cdn-integration-components)
+ [Prerequisites for CDN integration](#prerequisites)
+ [CDN integration setup steps](#cdn-integration-workflow)
+ [Required headers for MediaTailor CDN integration](#cdn-required-headers)
+ [Set up CDN routing behaviors for MediaTailor](cdn-routing-behaviors.md)
+ [Set up CDN mapping in MediaTailor](cdn-mapping-mediatailor.md)
+ [CDN integration security best practices for MediaTailor](cdn-security-best-practices.md)

# Set up CDN routing behaviors for MediaTailor
<a name="cdn-routing-behaviors"></a>

This section explains how to set up your content delivery network (CDN) to route different types of requests appropriately for AWS Elemental MediaTailor integration. Proper routing configuration ensures that manifest requests, content segments, and ad segments are handled correctly.

Configuring CDN routing behaviors is a critical step in creating an efficient content delivery pipeline. By setting up specific routing rules for different content types, you can optimize caching, improve delivery performance, and ensure personalized ad insertion works correctly.

For advanced routing scenarios using dynamic variables and configuration aliases, see [MediaTailor dynamic ad variables for ADS requests](variables.md). For information about preserving query parameters across CDN routing, see [MediaTailor manifest query parameters](manifest-query-parameters.md).

**Important**  
Failure to include CORS headers in either the cached object or on the CDN response to viewers can cause playback failures. 

## CDN routing behavior configuration
<a name="cdn-routing-configuration"></a>

Set up your CDN to route different types of requests appropriately.

### Content segment routing
<a name="content-segment-routing"></a>

Content segment routing directs requests for your actual content segments to your origin server. Like ad segment routing, content segment routing also requires proper CORS configuration to ensure smooth playback in web-based players.

For detailed configuration guidance, see the CloudFront example at [Precedence 4: Content origin path behavior](cf-comprehensive-configuration.md#cf-default-behavior). This example provides specific settings that you should follow for CloudFront or adapt for other CDNs.

Key configuration requirements for content segment routing include:
+ Use path patterns that match your content segment file extensions (like `*.ts`, `*.mp4`, or `*.m4s`)
+ Route requests to your content origin (such as an Amazon S3 Bucket or MediaPackage endpoint)
+ For optimal cache-hit ratio, include only query string parameters that cause your origin to modify the response in the cache key and forward the origin request 
+ Apply an appropriate cache policy with greater than 24-hour TTL values
+ Include CORS response headers to your viewers

### Ad segment routing
<a name="ad-segment-routing"></a>

Ad segment routing is critical for delivering personalized advertisements to viewers. When configuring ad segment routing, you must implement proper CORS (Cross-Origin Resource Sharing) handling to prevent issues that can cause playback failures in web-based players.

For detailed configuration guidance, see the CloudFront example at [Precedence 0: Ad segments path behavior](cf-comprehensive-configuration.md#cf-transcode-manage-behavior). This example provides specific settings that you should follow for CloudFront or adapt for other CDNs.

Key configuration requirements for ad segment routing include:
+ Use the path pattern `/tm/*` specifically for MediaTailor ad segments
+ Route requests to `segments.mediatailor.region.amazonaws.com`
+ For optimal cache-hit ratio, do not include any viewer request headers, cookies, or query string parameters in the cache key or in the origin request
+ Apply an appropriate cache policy with greater than 24-hour TTL values
+ Include CORS response headers to your viewers

### Manifest request routing
<a name="manifest-routing"></a>

To route multivariant playlist, media playlist, and MPD requests to MediaTailor, use the following general settings. For CloudFront configuration, see [Configuring manifest cache behavior](cloudfront-basic-setup.md#cf-manifest-behavior).

1. In your CDN configuration interface, create behaviors for different manifest types.

1. Set path patterns to match multivariant playlist and media playlist file extensions (`*.m3u8` for HLS) and MPD file extensions (`*.mpd` for DASH).

1. Configure the origin setting in your CDN to point to your MediaTailor configuration endpoint.

1. For ad insertion, disable caching of personalized multivariant playlists, media playlists, and MPDs. Because ad insertion provides personalized manifests, your CDN shouldn't cache them. If a different playback device than the one intended receives a cached playlist or MPD, it could result in issues with playback or tracking. For comprehensive caching guidance including TTL recommendations for all content types, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

1. Configure header forwarding for all headers. For minimum requirements, see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers).

1. Enable query string forwarding to pass ad targeting parameters.

------
#### [ HLS multivariant playlist ]

HLS multivariant playlist requests follow these formats:

```
https://<playback-endpoint>/v1/index/<hashed-account-id>/<origin-id>/<index>.m3u8
```

Example:

```
https://777788889999.mediatailor.us-east-1.amazonaws.com/v1/master/a1bc06b59e9a570b3b6b886a763d15814a86f0bb/Demo/assetId.m3u8
```

------
#### [ HLS media playlist ]

HLS media playlist requests follow these formats:

```
https://<playback-endpoint>/v1/manifest/<hashed-account-id>/<session-id>/<manifestNumber>.m3u8
```

Player requests to `https://CDN_Hostname/some/path/asset.m3u8` are routed to the MediaTailor path `https://mediatailor.us-west-2.amazonaws.com/v1/session/configuration/endpoint` based on the keyword `*.m3u8` in the request.

Example:

```
https://777788889999.mediatailor.us-east-1.amazonaws.com/v1/manifest/a1bc06b59e9a570b3b6b886a763d15814a86f0bb/c240ea66-9b07-4770-8ef9-7d16d916b407/0.m3u8
```

------
#### [ DASH MPD ]

DASH MPD requests follow these formats:

```
https://<playback-endpoint>/v1/dash/<hashed-account-id>/<origin-id>/<assetName>.mpd
```

Player requests to `https://CDN_Hostname/some/path/asset.mpd` are routed to the MediaTailor path `https://mediatailor.us-west-2.amazonaws.com/v1/dash/configuration/endpoint` based on the keyword `*.mpd` in the request.

Example:

```
https://777788889999.mediatailor.us-east-1.amazonaws.com/v1/dash/a1bc06b59e9a570b3b6b886a763d15814a86f0bb/Demo/0.mpd
```

------

## CDN routing best practices
<a name="cdn-routing-best-practices"></a>

When configuring CDN routing behaviors, follow these best practices to ensure optimal performance and reliability:

**Use specific path patterns**  
Create specific path patterns that accurately match your content structure to ensure proper routing.

**Prioritize behavior order**  
In most CDNs, behaviors are evaluated in order. Place more specific behaviors before more general ones.

**Test behavior patterns**  
Verify that your path patterns correctly match the expected requests before deploying to production.

**Document your configuration**  
Maintain documentation of your CDN routing behaviors to facilitate troubleshooting and future updates.

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

After configuring your CDN routing behaviors, the next step is to configure CDN mapping in MediaTailor. See [Set up CDN mapping in MediaTailor](cdn-mapping-mediatailor.md) for instructions.

# Set up CDN mapping in MediaTailor
<a name="cdn-mapping-mediatailor"></a>

This section explains how to configure AWS Elemental MediaTailor to use your content delivery network (CDN) domain names. After setting up your CDN routing behaviors, you need to update your MediaTailor configuration to ensure that manifests reference your CDN domain instead of directly referencing origin servers.

Configuring CDN mapping in MediaTailor ensures that all content and ad segment URLs in your manifests point to your CDN rather than directly to origin servers. This step is essential for creating a complete CDN delivery chain and maximizing the benefits of your CDN integration.

## CDN mapping configuration in MediaTailor
<a name="mediatailor-configuration"></a>

After setting up your CDN routing behaviors, configure MediaTailor to use your CDN domain names:

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

1. Select the configuration you want to update.

1. In the **Advanced settings** of the **CDN configuration** section, enter your CDN domain name in the **CDN content segment prefix** field.

1. If you're using a separate CDN domain for ad segments, enter it in the **CDN ad segment prefix** field.

1. Save your changes.

This configuration ensures that MediaTailor generates manifests with URLs that point to your CDN instead of directly to the origin or ad segment storage.

### Understanding base URL behavior
<a name="base-url-behavior"></a>

MediaTailor determines base URLs in manifests based on your CDN prefix configuration:
+ **CDN ad segment prefix configured**: Ad segments use the CDN prefix as the base URL.
+ **CDN ad segment prefix not configured**: Ad segments use the direct MediaTailor location as the base URL.
+ **CDN content segment prefix configured**: Content segments use the CDN prefix as the base URL.
+ **CDN content segment prefix not configured**: Content segments reference the original content origin.

#### DASH BaseURL handling
<a name="dash-baseurl-handling"></a>

For DASH manifests, MediaTailor manages `BaseURL` settings differently for content and ad segments:

**Content segments:**
+ **With CDN content segment prefix**: MediaTailor sets exactly one `BaseURL` at the `MPD` level using your specified prefix.
+ **Without CDN content segment prefix**: MediaTailor preserves existing `BaseURL` settings from the origin manifest, or adds one based on the origin `MPD` URL if none exist.

**Ad segments:**
+ **With CDN ad segment prefix**: Each ad period gets exactly one `BaseURL` using the configured prefix.
+ **Without CDN ad segment prefix**: Each ad period gets exactly one `BaseURL` pointing to the MediaTailor ad content server.

**Example CDN mapping example**  
If your content origin is `http://origin.com/contentpath/` and your CDN content segment prefix is `https://cdn.example.com/`, then a content segment that would normally be referenced as `http://origin.com/contentpath/subdir/content.ts` will appear in the manifest as `https://cdn.example.com/subdir/content.ts`.

## Important considerations
<a name="cdn-mapping-considerations"></a>

When configuring CDN mapping in MediaTailor, keep the following important considerations in mind:

**Use HTTPS for CDN prefixes**  
Always use HTTPS URLs for your CDN prefixes to ensure secure content delivery.

**Match CDN behavior paths**  
Ensure that the CDN prefixes you configure in MediaTailor match the path patterns you configured in your CDN behaviors.

**Consider regional CDNs**  
If you're using different CDN domains for different regions, you'll need to create separate MediaTailor configurations for each region.

**Verify domain ownership**  
Ensure that you have control over the CDN domains you configure in MediaTailor.

## Verify CDN mapping configuration
<a name="cdn-mapping-verification"></a>

After configuring CDN mapping in MediaTailor, verify that your configuration is working correctly:

1. Request a manifest through your CDN.

1. Examine the manifest content to verify that segment URLs reference your CDN domain.

1. Check that content segment URLs in the manifest point to your CDN domain.

1. Check that ad segment URLs in the manifest point to your CDN domain.

For comprehensive testing and validation procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md).

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

After configuring CDN mapping in MediaTailor, the next step is to implement security best practices for your CDN integration. See [CDN integration security best practices for MediaTailor](cdn-security-best-practices.md) for instructions.

# CDN integration security best practices for MediaTailor
<a name="cdn-security-best-practices"></a>

This section explains how to implement security best practices for your AWS Elemental MediaTailor content delivery network (CDN) integration. Proper security configuration helps protect your content and infrastructure from unauthorized access and potential threats.

Securing your CDN integration is crucial for protecting your content, preventing unauthorized access, and ensuring compliance with security requirements. Implementing these best practices helps create a robust security posture for your streaming workflow.

## CDN security configuration
<a name="cdn-security-settings"></a>

Before configuring your CDN routing and cache settings, implement these security best practices to protect your content and infrastructure:

### Transport security
<a name="transport-security"></a>

MediaTailor only uses HTTPS for all communication and does not allow HTTP connections. To ensure secure communication between all components in your streaming workflow, complete the following steps:

1. Configure HTTPS for all communication between your CDN and MediaTailor endpoints. MediaTailor requires HTTPS and will not accept HTTP connections.

1. Use TLS 1.2 or later for all HTTPS connections.

1. Configure your CDN to enforce HTTPS-only connections from viewers.

### Access control
<a name="access-control"></a>

To protect your content and infrastructure from unauthorized access, implement the following access controls:

1. Configure geo-restriction settings if you need to limit content access to specific regions.

1. Implement signed URLs or signed cookies for content that requires viewer authentication.

1. Set up IP-based allowlists for administrative access to CDN configuration.

### Security monitoring
<a name="security-monitoring"></a>

To detect and respond to security events effectively, implement the following monitoring practices:

1. Enable access logging for your CDN distribution.

1. Set up alerts for unusual traffic patterns or access attempts.

1. Regularly review security configurations and update as needed.

## Advanced security features
<a name="advanced-security-features"></a>

The following advanced security features provide enhanced protection for your CDN integration:

**Web Application Firewall (WAF)**  
If your CDN supports WAF functionality, configure it to protect against common web vulnerabilities and attacks.

**DDoS protection**  
Enable DDoS protection features provided by your CDN to mitigate distributed denial-of-service attacks.

**Origin access control**  
Configure your origin servers to accept requests only from your CDN to prevent direct access attempts.

**Content encryption**  
For highly sensitive content, consider implementing additional encryption mechanisms beyond transport security.

## Next steps
<a name="security-best-practices-next-steps"></a>

After implementing security best practices, the next step is to test and troubleshoot your CDN integration. See [Troubleshoot CDN integration](cdn-troubleshooting.md) for comprehensive testing and troubleshooting instructions.

# Set up SSAI with a CDN for personalized video advertising
<a name="ssai-cdn-workflow"></a>

This section provides comprehensive guidance for integrating AWS Elemental MediaTailor server-side ad insertion (SSAI) with a content delivery network (CDN). Follow these steps to set up, configure, and optimize your SSAI CDN integration.

Server-side ad insertion (SSAI) is a technology that seamlessly inserts personalized advertisements into video streams at the server level rather than the client level. When combined with a CDN, you create a robust, scalable solution for delivering personalized advertising to global audiences with minimal latency.

In this topic, we use the term *manifests* to refer collectively to multivariant playlists, media playlists, and MPDs.

## What you'll need
<a name="ssai-cdn-what-you-need"></a>

Before setting up MediaTailor ad insertion with a CDN, gather these required resources:

**AWS account and permissions**  
An AWS account with appropriate permissions to create and manage MediaTailor resources  
IAM permissions for MediaTailor, CloudFront (if using), and related services  
For detailed permission requirements, see [Security in AWS Elemental MediaTailor](security.md).

**Required services**  
AWS Elemental MediaTailor configured and running  
A content delivery network (CDN) account (Amazon CloudFront or third-party CDN)  
Origin server for your content (HLS or DASH)  
Ad decision server (ADS) that supports VAST or VMAP

**Content requirements**  
Content properly encoded and packaged in HLS or DASH format  
Ad break markers in your content (for VOD) or SCTE-35 markers (for live)

## Before you begin
<a name="ssai-cdn-before-you-begin"></a>

Complete these setup tasks before implementing MediaTailor ad insertion with a CDN:

1. Configure network connectivity between your CDN, MediaTailor, and origin servers

1. Set up HTTPS for secure content delivery

1. Configure DNS settings for your CDN domain

1. For basic MediaTailor setup, complete the steps in [Setting up](setting-up.md) and [Getting started with MediaTailor ad insertion](getting-started-ad-insertion.md).

### Knowledge prerequisites
<a name="ssai-cdn-knowledge-prerequisites"></a>

To successfully implement this solution, you should have:
+ Understanding of streaming protocols (HLS/DASH)
+ Basic knowledge of CDN configuration principles
+ Familiarity with ad insertion concepts

## Benefits of CDN integration
<a name="ssai-cdn-benefits"></a>

Integrating SSAI with a CDN delivers these key benefits:

**Improved viewer experience**  
Properly configured CDNs reduce buffering, startup times, and playback errors during ad transitions. This results in higher viewer engagement and satisfaction.

**Cost reduction**  
Efficient caching strategies minimize origin requests. This reduces data transfer costs and origin server load, particularly important for high-volume ad-supported content.

**Scalability**  
Optimized CDN configurations handle traffic spikes during popular events without degrading performance, ensuring your personalized ads are delivered even during peak viewing times.

**Global reach**  
Properly configured CDNs deliver content with low latency to viewers worldwide, regardless of their location, expanding your potential audience.

**Seamless ad transitions**  
Optimized CDN configuration ensures smooth transitions between content and ads, creating a broadcast-quality viewing experience.

The following topics provide comprehensive guidance on configuring MediaTailor with a CDN for optimal performance.

**Topics**
+ [What you'll need](#ssai-cdn-what-you-need)
+ [Before you begin](#ssai-cdn-before-you-begin)
+ [Benefits of CDN integration](#ssai-cdn-benefits)
+ [Understand CDN architecture](ssai-cdn-architecture-overview.md)
+ [Set up basic ad insertion](configuring-ssai-cdn.md)
+ [SSAI with channel assembly](ssai-ca-integration.md)
+ [Optimize CDN performance](ssai-cdn-performance.md)
+ [Monitor CDN operations](ssai-cdn-monitor.md)
+ [Troubleshoot ad insertion with CDNs](troubleshooting-ssai-cdn.md)

# Understand ad insertion architecture for CDN and MediaTailor integrations
<a name="ssai-cdn-architecture-overview"></a>

This section explains the concepts and architecture of server-side ad insertion (SSAI) with content delivery networks (CDNs) for AWS Elemental MediaTailor. You'll learn how dynamic ad insertion and manifest manipulation work together to enable effective video monetization.

Server-side ad insertion (SSAI) with MediaTailor allows you to:
+ Insert personalized advertising into your video streams at defined ad break points
+ Target ads precisely based on viewer data
+ Eliminate the need for client-side ad insertion technology

When combined with a CDN, you can deliver these personalized streams to viewers with improved performance and scalability, enhancing your video monetization strategy.

The recommended architecture for ad insertion with a CDN positions the CDN between viewers and ad insertion, with ad insertion accessing content directly from your origin. This architecture provides the following benefits for both content delivery and video monetization:
+ Effective caching of content and ad segments
+ Reduced request load on MediaTailor
+ Improved delivery speed to viewers
+ Simplified URL management
+ Consistent delivery of personalized advertising across devices

In this recommended architecture:

1. Viewers request manifests from the CDN

1. CDN forwards requests to ad insertion

1. Ad insertion requests content manifests from the origin

1. Ad insertion requests ads from the ad decision server (ADS)

1. Ad insertion personalizes manifests by replacing the ad markers (from the origin manifest) with URLs that point to targeted ad segments for the specific viewer (from the ADS)

1. Ad insertion returns the personalized manifests containing ad segment URLs to the CDN, which forwards them to viewers

1. Viewers request segments through the CDN

1. CDN routes segment requests based on the segment type: 
   + Content segment requests go to the content origin
   + Ad segment requests go to MediaTailor 

This architecture ensures optimal performance while maintaining the security and flexibility benefits of using a CDN.

![\[Diagram showing CDN positioned between client players and AWS Elemental MediaTailor Ad Insertion\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/cdn-recommended-positioning.png)


**Note**  
This flow varies slightly between VOD and live content. For VOD, manifests can be cached longer, while live content requires more frequent manifest updates to maintain stream continuity.

The key difference between VOD and live content caching:

VOD content  
Set longer TTL values (minutes to hours) for manifests because they don't change frequently

Live content  
Set shorter TTL values (seconds) for manifests to ensure viewers receive the most current stream segments

We don't recommend that you position a CDN between your content origin and AWS Elemental MediaTailor. Doing so can introduce several technical challenges:

Cache-key collisions  
Configure your CDN to properly handle query parameters. This prevents MediaTailor from receiving incorrect manifests when requesting the same manifest with different query parameters.

Gzip compression issues  
If you experience manifest parsing errors, ensure your CDN delivers properly formatted manifests to MediaTailor. Some CDNs may deliver corrupt gzip payloads that can cause parsing failures. If this occurs, you may need to disable compression between your CDN and MediaTailor while maintaining compression for cost savings elsewhere in your workflow.

Manifest freshness  
For live streams, configure your CDN to deliver current manifests to MediaTailor. This prevents synchronization issues between content and ads.

Performance optimization  
Minimize network hops and potential cache misses to reduce playback start-up times.

Cache management  
Implement simplified cache invalidation strategies, especially for live content where manifests update frequently.

In this sub-optimal architecture:

1. Viewers request multivariant playlists, media playlists, or MPDs directly from AWS Elemental MediaTailor.

1. MediaTailor requests content manifests (multivariant playlists, media playlists, or MPDs) through the CDN.

1. The CDN forwards requests to the origin server.

1. The origin server returns multivariant playlists, media playlists, or MPDs to the CDN.

1. The CDN forwards multivariant playlists, media playlists, or MPDs to MediaTailor.

1. MediaTailor requests ads from the ad decision server (ADS).

1. MediaTailor personalizes manifests by inserting ads into multivariant playlists, media playlists, or MPDs and delivers them directly to viewers.

1. This architecture introduces additional latency, potential caching issues, and complicates troubleshooting.

![\[Diagram showing CDN positioned between content origin and MediaTailor\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/cdn-not-recommended-positioning.png)


## Request and response flow
<a name="understand-request-flow"></a>

When implementing dynamic ad insertion with a CDN, configure your system to support this request and response flow:

1. Configure your player to request multivariant playlists (HLS) or MPDs (DASH) from your CDN with MediaTailor as the manifest origin.

1. Set up your CDN to forward all multivariant playlist, media playlist, and MPD requests to MediaTailor, including all query parameters and headers.

1. Ensure MediaTailor can communicate with your ad decision server (ADS), passing along query parameters and headers.

1. Configure your ADS to use query parameters to determine which ads to insert.

1. Set up the CDN prefix on the MediaTailor playback configuration so MediaTailor can substitute CDN domain names for content and ad segment URL prefixes.

1. Configure your CDN to forward personalized multivariant playlists, media playlists, and MPDs from MediaTailor to the requesting player.

1. Set up your CDN to translate segment URLs, forwarding content segment requests to the origin server and ad requests to the Amazon S3 bucket where MediaTailor stores transcoded ads.

### CDN terminology for ad insertion
<a name="ssai-cdn-terminology"></a>

Understanding these key terms will help you implement and troubleshoot your ad insertion CDN integration:

Origin CDN and edge CDN  
**Origin CDN**: A CDN positioned between MediaTailor and your content origin. It caches content segments to reduce load on your origin servers. In a multi-CDN architecture, this is the first CDN layer that interfaces directly with the origin.  
**Edge CDN**: A CDN positioned between viewers and MediaTailor. It delivers personalized manifests and content to viewers. In a multi-CDN architecture, this is the outermost CDN layer that interfaces directly with viewers.

CDN configuration terms  
**Cache behavior**: Rules that determine how a CDN handles different types of requests. These rules include:  
+ Caching duration settings
+ Origin routing configurations
+ Request handling parameters
**TTL (Time To Live)**: The duration for which content remains valid in a CDN cache before it needs to be refreshed from the origin.  
**Cache key**: The unique identifier used by a CDN to store and retrieve cached content. It typically includes:  
+ URL path
+ Query parameters
+ Selected headers
**Origin shield**: An intermediate caching layer between CDN edge locations and your origin server. It reduces the number of requests to your origin.  
**Request collapsing**: A CDN feature that combines multiple simultaneous requests for the same content into a single origin request.

MediaTailor-specific CDN terms  
**CDN content segment prefix**: The CDN domain name that AWS Elemental MediaTailor uses when generating URLs for content segments in manifests.  
**CDN ad segment prefix**: The CDN domain name that MediaTailor uses when generating URLs for ad segments in manifests.

For more information about CDN configuration with MediaTailor, see [Set up CDN integration](cdn-configuration.md).

**Note**  
These terms are consistent with those used in channel assembly documentation. For channel assembly terminology, see [CDN terminology for channel assembly](channel-assembly-cdn-architecture.md#cdn-terminology).

# Set up basic MediaTailor SSAI with a CDN for optimal ad delivery
<a name="configuring-ssai-cdn"></a>

This section provides step-by-step instructions for configuring AWS Elemental MediaTailor dynamic ad insertion with a content delivery network (CDN) to optimize your video monetization workflow.

For advanced ad server configuration using dynamic variables, see [MediaTailor dynamic ad variables for ADS requests](variables.md). For information about passing parameters through CDNs for ad targeting, see [MediaTailor manifest query parameters](manifest-query-parameters.md).

For conceptual information about SSAI with CDNs, see [Understand ad insertion architecture for CDN and MediaTailor integrations](ssai-cdn-architecture-overview.md).

## Prerequisites
<a name="prerequisites-ad-insertion-cdn"></a>

Before setting up ad insertion with a CDN, ensure you have:
+ An active AWS Elemental MediaTailor configuration
+ A content origin server delivering HLS or DASH content with appropriate ad markers

  For information about ad markers, see [Understanding ad insertion behavior](ad-behavior.md).
+ An ad decision server (ADS) that supports VAST or VMAP for ad targeting
+ A CDN account (such as Amazon CloudFront or another CDN provider)
+ Basic knowledge of manifest manipulation and dynamic ad insertion concepts

## Step 1: Configure CDN caching for optimal ad delivery
<a name="configure-cdn-caching"></a>

Proper CDN caching configuration is critical for optimal performance of your video monetization workflow. The caching requirements differ between server-side ad insertion (SSAI) and server-guided ad insertion (SGAI). Use these recommended settings to ensure efficient delivery of both content and personalized advertising:

### SSAI CDN caching settings
<a name="ssai-caching-settings"></a>

For server-side ad insertion workflows, proper caching configuration is critical for optimal performance. SSAI requires specific TTL values and cache key settings to ensure personalized manifests are not cached while segments are cached efficiently.

For detailed SSAI caching settings including TTL values, path patterns, and cache key configurations, see [Server-side ad insertion (SSAI) caching](cdn-optimize-caching.md#ssai-caching-optimization) in the CDN optimization guide.

Key caching principles for SSAI:
+ **Manifests**: Set TTL to 0 seconds to prevent caching of personalized content
+ **Segments**: Cache aggressively (24\$1 hours) to reduce origin load
+ **Cache keys**: Include all query parameters for manifests, URL path only for segments

### SGAI CDN caching settings
<a name="sgai-caching-settings"></a>

For server-guided ad insertion workflows, caching requirements differ from SSAI because SGAI manifests can be cached for short periods while still providing personalized ad experiences.

For comprehensive SGAI caching settings including VOD and live TTL values, see the optimization guide's caching tables. SGAI allows for better cache efficiency than SSAI while maintaining ad personalization capabilities.

Key SGAI caching differences:
+ **Manifests**: Can be cached for short periods (5-30 minutes for VOD, 2-10 seconds for live)
+ **Segments**: Cache aggressively like SSAI (24\$1 hours for most content)
+ **Performance benefit**: Better cache hit ratios than SSAI due to cacheable manifests

For Amazon CloudFront, you can implement these settings using cache behaviors with different TTL values and cache key policies. For other CDNs, refer to their specific documentation for implementing similar caching rules.

## Step 2: Implement hybrid approaches (if needed)
<a name="implement-hybrid-approach"></a>

If your architecture requires a hybrid approach with a separate CDN or caching layer between the content origin and MediaTailor:

1. Implement clear separation of concerns in your CDN configuration.

1. Configure specific CDN settings to prevent the technical issues described in the previous section.

1. Thoroughly test your configuration to verify that manifest personalization functions correctly.

1. Monitor performance metrics to ensure optimal delivery of multivariant playlists, media playlists, MPDs, and segments.

When implementing a hybrid approach, consider these specific configurations:
+ For the CDN between content origin and MediaTailor:
  + Configure compression passthrough for manifest files to preserve the original compression state from your origin
  + Include all query parameters in the cache key
  + Set short TTL values for live content manifests
+ For the CDN between MediaTailor and viewers:
  + Configure longer cache times for ad segments
  + Set appropriate TTLs for personalized manifests
  + Implement proper origin routing for content vs. ad segments

## Step 3: Complete your CDN setup
<a name="complete-cdn-setup"></a>

After choosing your architecture and understanding the request flow, complete your setup by following the detailed configuration steps in [Set up CDN integration](cdn-configuration.md).

For specific CDN providers, refer to these additional resources:
+ Amazon CloudFront: See [CloudFront integration](cloudfront-specific-recommendations.md) for CloudFront-specific configuration steps
+ Other CDNs: Apply the general principles outlined in this guide, adapting them to your specific CDN's configuration options

## Step 4: Verify your configuration
<a name="verification-steps"></a>

After completing your CDN setup, verify that your dynamic ad insertion workflow is functioning correctly:

1. Test playback through your CDN with a sample player

1. Verify that personalized advertising is inserted correctly at designated ad break points

1. Check CDN logs to confirm proper request routing

1. Monitor cache hit rates to ensure optimal performance for both content and ad segments

1. Confirm that ad targeting parameters are being properly passed through the workflow

For comprehensive testing and validation procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md). For detailed information on monitoring your SSAI implementation, see [Monitor operations for CDN and MediaTailor integrations](ssai-cdn-monitor.md). To optimize performance, see [Optimize performance for CDN and MediaTailor integrations](ssai-cdn-performance.md).

# Integrate MediaTailor SSAI with channel assembly for monetized linear channels
<a name="ssai-ca-integration"></a>

This topic explains how to combine AWS Elemental MediaTailor server-side ad insertion with channel assembly and content delivery network (CDN) integration. This integration enables you to:
+ Create monetized linear channels with personalized advertising
+ Deliver targeted ads to different viewers watching the same content
+ Maintain broadcast-quality viewing experiences

## Benefits of combining SSAI with channel assembly
<a name="ssai-ca-integration-benefits"></a>

Integrating SSAI with channel assembly provides several key benefits:

Monetization of linear channels  
Insert personalized ads into your linear channels to generate revenue from your content library. You can monetize both live and VOD content within a single linear stream.

Personalized advertising  
Deliver different ads to different viewers watching the same channel content. This targeted approach increases ad relevance and potential revenue compared to traditional broadcast advertising.

Simplified ad break management  
Define ad break points in your channel assembly programs without needing to condition the content with SCTE-35 markers. This makes it easier to insert ads at natural break points in your content.

Broadcast-quality experience  
MediaTailor maintains a high-quality viewing experience with seamless transitions between content and ads. Server-side ad insertion eliminates many common issues such as:  
+ Buffering during ad transitions
+ Ad blockers preventing monetization
+ Inconsistent playback quality

Scalable delivery  
When combined with a CDN, this integration can scale to millions of concurrent viewers without degradation in performance or personalization capabilities.

## Architecture overview
<a name="ssai-ca-integration-architecture"></a>

The architecture for combining SSAI with channel assembly typically involves these components:
+ Channel assembly: Creates linear channels from VOD and live content, and inserts slate content that creates ad markers in the generated manifest
+ Ad insertion: Recognizes ad break points and inserts URLs pointing to personalized ad segments in the manifest
+ Ad decision server (ADS): Determines which ads to insert for each viewer
+ Content delivery network (CDN): Delivers the assembled content and ad segments to viewers
+ Origin server: Stores the VOD and live content segments

In this architecture:

1. Channel assembly creates a linear channel from your VOD and live content, and inserts slate content that creates the ad markers in the generated manifest

1. When a viewer requests the channel, ad insertion recognizes the ad breaks that were inserted into the linear channel

1. Ad insertion makes the call to the ADS to receive the list of ads, transcodes them, and inserts URLs pointing to the transcoded ad segments into the personalized manifest

1. The CDN delivers the personalized stream to the viewer

The following diagram illustrates this workflow:

![\[Diagram showing CDN integration with both channel assembly and ad insertion\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/ca-ssai-comb-cdn.png)


## Setting up the integration
<a name="ssai-ca-integration-setup"></a>

To set up SSAI with channel assembly:

1. Configure your edge CDN to accept manifest requests from viewers and forward them to AWS Elemental MediaTailor ad insertion.

1. Set up MediaTailor ad insertion to forward requests to your origin CDN.

1. Configure your origin CDN to forward requests to MediaTailor channel assembly.

1. Set up MediaTailor channel assembly to generate dynamic manifests based on the current schedule.

1. Configure your origin CDN to forward the assembled manifests to MediaTailor ad insertion.

1. Set up MediaTailor ad insertion to request ad decisions from your ad decision server at ad break points.

1. Configure MediaTailor ad insertion to personalize manifests by replacing the ad markers (from channel assembly) with URLs pointing to targeted ad segments (from the ADS).

1. Set up your edge CDN to deliver personalized manifests to viewers.

1. Configure your CDN architecture to handle both content and ad segment requests efficiently.

## Defining ad breaks in channel assembly
<a name="ssai-ca-integration-adbreaks"></a>

When creating programs in channel assembly, you can define ad breaks in several ways:

Program transitions  
Insert ads between programs in your channel schedule. This is the simplest approach and ensures ads don't interrupt program content.

SCTE-35 markers  
If your VOD content contains SCTE-35 markers, channel assembly can preserve these markers, and ad insertion can use them as ad break points.

Time-based insertion  
Define ad breaks at specific time points within programs. This allows you to insert ads at natural break points in your content.

For detailed information on creating programs with ad breaks, see [Working with programs](https://docs.aws.amazon.com/mediatailor/latest/ug/channel-assembly-programs.html).

## CDN caching considerations
<a name="ssai-ca-integration-caching"></a>

For optimal performance when combining channel assembly and SSAI with a CDN:
+ Configure cache behaviors that distinguish between channel assembly and SSAI requests
+ Set appropriate TTL values for manifests and segments as recommended in [Step 1: Configure CDN caching for optimal ad delivery](configuring-ssai-cdn.md#configure-cdn-caching)
+ Ensure proper routing between channel assembly, ad insertion, and your CDN origins
+ Monitor the performance metrics for both channel assembly and ad insertion components


**Recommended caching settings for combined implementation**  

| Content type | TTL | Cache key elements | 
| --- | --- | --- | 
| Channel assembly manifests | 0 seconds | URL path \$1 query parameters | 
| SSAI personalized manifests | 0 seconds | URL path \$1 all query parameters | 
| Content segments | 24\$1 hours | URL path only | 
| Ad segments | 24\$1 hours | URL path only | 

## Monitoring the integrated solution
<a name="ssai-ca-integration-monitoring"></a>

To ensure your integrated solution is performing optimally, monitor these key metrics:

Channel assembly metrics  
Monitor manifest generation time, program transitions, and any errors in the channel assembly process.

Ad insertion metrics  
Track ad fill rate, ad decision server response times, and ad insertion errors.

CDN metrics  
Monitor cache hit rates, origin request volume, and response latency for both content and ad segments.

Viewer experience metrics  
Track rebuffering events, startup times, and viewer engagement, especially during ad transitions.

For detailed information on monitoring, see [Monitor operations for CDN and MediaTailor integrations](ssai-cdn-monitor.md) and [Monitor MediaTailor channel assembly CDN operations](ca-cdn-monitor.md).

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

When troubleshooting issues with the integrated solution, consider these common problems:

Ad break synchronization issues  
If ads are not appearing at the expected break points, verify that the ad break definitions in your channel assembly programs are correctly configured and that ad insertion is properly identifying these break points.

Manifest delivery errors  
If viewers are experiencing playback issues, check that the CDN is correctly forwarding manifest requests between channel assembly and ad insertion, and that the cache settings are appropriate for the dynamic nature of these manifests.

Segment routing problems  
If content or ad segments are not loading, verify that the CDN is correctly routing segment requests to the appropriate origins and that the segment URLs in the manifests are correctly formatted.

Performance degradation  
If viewers are experiencing buffering or high latency, check the CDN cache hit rates and origin request volumes to identify potential bottlenecks in the delivery pipeline.

For more troubleshooting guidance, see [Troubleshoot MediaTailor SSAI with CDNs for uninterrupted ad delivery](troubleshooting-ssai-cdn.md).

## Best practices
<a name="ssai-ca-integration-best-practices"></a>

Follow these best practices for a successful integration of SSAI with channel assembly:
+ **Test thoroughly**: Test the integrated solution with various content types, ad scenarios, and viewer conditions before deploying to production.
+ **Monitor continuously**: Set up comprehensive monitoring and alerting to quickly identify and address any issues that arise.
+ **Optimize caching**: Regularly review and adjust your CDN caching settings based on actual usage patterns and performance metrics.
+ **Plan for scale**: Design your architecture to handle peak traffic loads, especially for popular channels or events.
+ **Consider redundancy**: Implement redundancy in critical components to ensure high availability of your linear channels.
+ **Optimize ad transitions**: Ensure smooth transitions between content and ads by using consistent encoding profiles and segment durations.

## Related information
<a name="ssai-ca-integration-related"></a>

For more information about integrating SSAI with channel assembly, see:

Channel assembly documentation  
[Using AWS Elemental MediaTailor to create linear assembled streams](channel-assembly.md) - Learn about channel assembly concepts  
[Channel assembly with CDN](ca-cdn-wflw.md) - Set up channel assembly with a CDN

SSAI documentation  
[Ad insertion with CDN](ssai-cdn-workflow.md) - Set up ad insertion with a CDN  
[Understand ad insertion architecture for CDN and MediaTailor integrations](ssai-cdn-architecture-overview.md) - Understand ad insertion CDN architecture

CDN configuration  
[Set up CDN integration](cdn-configuration.md) - General CDN configuration guidance  
[CloudFront integration](cloudfront-specific-recommendations.md) - CloudFront specific configuration

# Optimize performance for CDN and MediaTailor integrations
<a name="ssai-cdn-performance"></a>

Maximize the performance of your AWS Elemental MediaTailor ad insertion implementation by optimizing your content delivery network (CDN) configuration. These settings ensure efficient content delivery and optimal viewer experience.

For detailed caching and routing optimization guidance specific to SSAI implementations, see [CDN performance optimization](cdn-optimization.md). The consolidated optimization guide provides comprehensive caching settings, request routing configuration, and performance benchmarks that apply to all MediaTailor CDN integrations.

## Common performance challenges
<a name="ssai-cdn-performance-challenges"></a>

SSAI implementations with CDNs can face several performance challenges:

Manifest manipulation overhead  
MediaTailor performs real-time manifest manipulation, which can introduce latency if not optimized properly. The following can introduce latency:  
+ Processing time for ad decision server (ADS) requests
+ Time required to modify manifests with ad segment references
+ Additional processing for personalization

Cache efficiency issues  
Personalized manifests can reduce CDN cache efficiency because:  
+ Each viewer may receive a unique manifest
+ Session parameters can fragment the cache
+ Dynamic content requires careful cache configuration

Origin load spikes  
Improper caching can lead to origin load spikes during:  
+ High-traffic events
+ Cache refreshes
+ CDN configuration changes

Ad-related playback issues  
Ad insertion can cause playback disruptions such as:  
+ Buffering during ad transitions
+ Quality differences between content and ads
+ Playback failures when ads cannot be retrieved

For comprehensive performance optimization guidance including caching strategies, request routing, performance benchmarks, and advanced optimization techniques, see [CDN performance optimization](cdn-optimization.md). The consolidated optimization guide provides detailed settings and benchmarks that apply to all MediaTailor CDN integrations, including SSAI implementations.

## Best practices summary
<a name="ssai-cdn-performance-best-practices"></a>

Follow these best practices to ensure optimal SSAI performance with CDNs:

Architecture best practices  
+ Choose the right architectural pattern for your scale and requirements
+ Deploy services in close proximity to minimize latency
+ Implement redundancy for critical components

Caching best practices  
+ Use different caching strategies for different content types
+ Optimize cache keys to balance personalization and efficiency
+ Set appropriate TTLs based on content type and update frequency. For detailed TTL recommendations, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

Ad delivery best practices  
+ Optimize ADS interactions with timeouts and fallbacks
+ Prepare ads to match content specifications
+ Implement efficient ad segment delivery

Monitoring best practices  
+ Monitor all components of your SSAI implementation
+ Set up alerts for performance degradation
+ Regularly review and optimize your configuration

## Complete optimization guidance
<a name="ssai-optimization-reference"></a>

For comprehensive CDN optimization guidance including detailed caching strategies, request routing configuration, performance benchmarks, and advanced optimization techniques, see [CDN performance optimization](cdn-optimization.md). The consolidated optimization guide provides complete settings and benchmarks that apply to all MediaTailor CDN integrations, including SSAI implementations.

# Monitor operations for CDN and MediaTailor integrations
<a name="ssai-cdn-monitor"></a>

AWS Elemental MediaTailor provides robust analytics capabilities that, when combined with content delivery network (CDN) metrics, offer comprehensive insights into your SSAI implementation. This topic covers:

For comprehensive CDN monitoring guidance including essential metrics, monitoring tools setup, alert configuration, and troubleshooting strategies that apply to all MediaTailor implementations, see [CDN monitoring](cdn-monitoring.md). This topic focuses on SSAI-specific monitoring requirements and ad insertion analytics.
+ Monitoring strategies for SSAI and CDN integration
+ Analytics tools and data collection methods
+ Data-driven optimization techniques

## Key metrics for SSAI with CDNs
<a name="ssai-cdn-monitor-metrics"></a>

To effectively monitor your SSAI implementation with CDNs, track these essential metrics:

Ad insertion metrics  
**Ad fill rate**: The percentage of ad opportunities that were successfully filled with ads.  
**Ad error rate**: The percentage of ad requests that resulted in errors.  
**Ad response time**: How long it takes for the ad decision server to respond to ad requests.  
**Ad duration accuracy**: How closely the actual duration of inserted ads matches the expected duration.

Viewer experience metrics  
**Rebuffering ratio**: The percentage of viewing time spent buffering.  
**Start-up time**: How long it takes for video playback to begin.  
**Ad transition smoothness**: How seamlessly the player transitions between content and ads.  
**Session duration**: How long viewers watch before abandoning the stream.

## Analytics tools and integration
<a name="ssai-cdn-monitor-tools"></a>

Combine these tools to create a comprehensive analytics solution for your SSAI implementation:

AWS Elemental MediaTailor server-side metrics  
MediaTailor provides built-in metrics through Amazon CloudWatch that track ad requests, responses, and errors. These metrics can be viewed in the CloudWatch console or integrated into custom dashboards.  
Key MediaTailor metrics include:  
+ `AdDecisionServer.Ads`: The number of ads returned by the ad decision server.
+ `AdDecisionServer.Duration`: The total duration of ads returned by the ad decision server.
+ `AdDecisionServer.Errors`: The number of errors returned by the ad decision server.
+ `AdDecisionServer.Latency`: The response time of the ad decision server.
For a complete list of MediaTailor metrics, see [Monitoring MediaTailor with Amazon CloudWatch](https://docs.aws.amazon.com/mediatailor/latest/ug/monitoring-cloudwatch.html).

CDN analytics  
CDN providers offer detailed analytics on content delivery performance. For Amazon CloudFront, use CloudWatch metrics and Amazon CloudFront access logs to analyze delivery patterns.  
Important CDN metrics to monitor:  
+ Request count by content type (manifests vs. segments)
+ Cache hit ratio for different content types
+ Geographic distribution of viewers
+ Error rates by error code

Client-side tracking  
Implement client-side tracking to gather viewer experience metrics that aren't available server-side:  
+ Player events (play, pause, seek, buffer)
+ Ad view completion rates
+ Quality of service metrics (resolution changes, bitrate)
+ Viewer engagement patterns
Consider using MediaTailor client-side tracking to collect and report these metrics.

Integrated dashboards  
Create comprehensive dashboards that combine metrics from multiple sources:  
+ Use CloudWatch dashboards to combine MediaTailor and CloudFront metrics
+ Consider third-party analytics platforms for more advanced visualization
+ Set up cross-service correlation to identify relationships between metrics

## Implementing a monitoring strategy
<a name="ssai-cdn-monitor-implementation"></a>

Follow these steps to implement a comprehensive monitoring strategy for your SSAI with CDN implementation:

1. **Set up basic monitoring**
   + Enable CloudWatch metrics for MediaTailor
   + Configure CDN logging and metrics collection
   + Implement client-side tracking in your video player

1. **Create custom dashboards**
   + Build a CloudWatch dashboard that combines key metrics
   + Include visualizations for ad fill rate, CDN performance, and viewer experience
   + Add annotations for important events (configuration changes, major broadcasts)

1. **Configure alerts**
   + Set up CloudWatch alarms for critical metrics
   + Create composite alarms that trigger on multiple related conditions
   + Configure notification channels (email, SMS, Amazon SNS)

1. **Implement automated responses**
   + Use CloudWatch Events to trigger automated responses to common issues
   + Create runbooks for manual intervention when needed
   + Document troubleshooting procedures for different alert scenarios

**Example Creating a comprehensive SSAI monitoring dashboard**  
This example shows how to create a CloudWatch dashboard that combines MediaTailor and CloudFront metrics:  

```
{
  "widgets": [
    {
      "type": "metric",
      "properties": {
        "metrics": [
          [ "AWS/MediaTailor", "AdDecisionServer.Ads", "Configuration", "your-config-name" ],
          [ ".", "AdDecisionServer.Errors", ".", "." ]
        ],
        "period": 300,
        "stat": "Sum",
        "region": "us-west-2",
        "title": "Ad Decision Server Performance"
      }
    },
    {
      "type": "metric",
      "properties": {
        "metrics": [
          [ "AWS/CloudFront", "Requests", "DistributionId", "your-distribution-id" ],
          [ ".", "4xxErrorRate", ".", "." ],
          [ ".", "5xxErrorRate", ".", "." ]
        ],
        "period": 300,
        "stat": "Average",
        "region": "us-east-1",
        "title": "CDN Performance"
      }
    }
  ]
}
```

## Data-driven optimization
<a name="ssai-cdn-monitor-optimization"></a>

Use the analytics data you collect to optimize your SSAI implementation:

CDN cache optimization  
Analyze cache hit ratios to identify opportunities for improvement:  
+ Adjust TTL settings based on content type and update frequency. For detailed TTL recommendations, see [Step 1: Configure CDN caching for optimal ad delivery](configuring-ssai-cdn.md#configure-cdn-caching).
+ Optimize cache key settings to improve cache efficiency
+ Consider implementing origin shield for multi-layered caching

Ad delivery optimization  
Use ad performance metrics to improve ad delivery:  
+ Identify and address common ad insertion errors
+ Optimize ad decision server response times
+ Adjust ad targeting parameters based on fill rate analysis

Viewer experience optimization  
Improve the viewer experience based on client-side metrics:  
+ Analyze drop-off patterns during ad breaks
+ Optimize ad transition points for smoother playback
+ Adjust ad frequency and duration based on viewer engagement data

Cost optimization  
Balance performance and cost considerations:  
+ Analyze bandwidth usage patterns to optimize CDN costs
+ Consider price class adjustments for CloudFront distributions
+ Evaluate the cost-benefit of different caching strategies

## Best practices
<a name="ssai-cdn-monitor-best-practices"></a>

Follow these best practices for effective SSAI monitoring and analytics:
+ **Establish baselines**: Collect metrics during normal operation to establish performance baselines that can be used for comparison during troubleshooting.
+ **Implement multi-level monitoring**: Monitor at different levels of your architecture (origin, CDN, player) to get a complete picture of performance.
+ **Correlate metrics across services**: Look for relationships between metrics from different services to identify root causes of issues.
+ **Use anomaly detection**: Implement CloudWatch anomaly detection to automatically identify unusual patterns in your metrics.
+ **Regularly review and refine**: Schedule regular reviews of your monitoring strategy and adjust based on changing requirements and new insights.
+ **Document findings and actions**: Maintain a record of optimization efforts and their results to build institutional knowledge.

## Related information
<a name="ssai-cdn-monitor-related"></a>

For more information about monitoring and analytics for SSAI with CDNs, see:
+ [Optimize performance for CDN and MediaTailor integrations](ssai-cdn-performance.md) for performance optimization techniques
+ [Troubleshoot MediaTailor SSAI with CDNs for uninterrupted ad delivery](troubleshooting-ssai-cdn.md) for troubleshooting common issues
+ [Monitoring MediaTailor with Amazon CloudWatch](https://docs.aws.amazon.com/mediatailor/latest/ug/monitoring-cloudwatch.html) for detailed information about MediaTailor metrics
+ [Viewing CloudFront and edge function metrics](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/viewing-cloudfront-metrics.html) for information about CloudFront metrics

# Troubleshoot MediaTailor SSAI with CDNs for uninterrupted ad delivery
<a name="troubleshooting-ssai-cdn"></a>

This section provides solutions for common issues when using AWS Elemental MediaTailor dynamic ad insertion with a content delivery network (CDN). These solutions will help you troubleshoot problems with your video monetization through personalized advertising.

For comprehensive CDN troubleshooting guidance including cache performance issues, HTTP error resolution, testing procedures, and diagnostic techniques that apply to all MediaTailor implementations, see [Troubleshoot CDN integration](cdn-troubleshooting.md). This section focuses on SSAI-specific troubleshooting requirements and ad insertion issues.

If you encounter issues with your CDN and SSAI setup, check these common problems:

Personalized advertising not appearing in stream  
Verify that your ADS responds correctly and that AWS Elemental MediaTailor communicates with it. Check these potential issues:  
+ Ad targeting query parameters not properly forwarded through your CDN
+ Ad break points incorrectly defined in your content
+ ADS connectivity or response problems

Playback errors at ad break points  
Ensure that ad segments are properly transcoded to match your content bitrates and resolutions. Check these common issues:  
+ CDN incorrectly routing requests for ad segments
+ Manifest manipulation errors at transition points
+ Mismatched encoding profiles between content and ads

Stale manifests  
For live content, verify that your CDN cache TTL settings are appropriate. For personalized manifests, use TTL of 0 seconds. Consider implementing cache invalidation for rapidly changing manifests. For comprehensive TTL guidance, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

High latency  
Check your CDN configuration for optimal routing. Ensure that your CDN has edge locations near your viewers for best performance.

## Advanced troubleshooting
<a name="advanced-troubleshooting"></a>

For more complex issues, try these advanced troubleshooting techniques:

Inconsistent ad targeting behavior  
Check for query parameter inconsistencies between player requests and ADS requests. Ensure all required targeting parameters are properly passed through the CDN.

CDN cache inconsistencies  
Verify cache key configurations to ensure proper content differentiation. Consider implementing cache purging for critical manifest updates.

Ad tracking failures  
Check that beacon URLs are properly forwarded and not blocked by the CDN. Verify that client players can reach the tracking endpoints.

## Performance optimization
<a name="performance-optimization"></a>

To optimize the performance of your dynamic ad insertion and video monetization workflow:
+ Fine-tune TTL settings based on content type and viewer patterns. For detailed TTL recommendations, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).
+ Implement geographic routing to minimize latency for global audiences
+ Consider using multiple CDNs for redundancy and optimal performance
+ Monitor cache hit ratios and adjust configurations accordingly
+ Optimize manifest manipulation processes to reduce processing time at ad break points
+ Pre-transcode ads to match common content profiles for seamless personalized advertising insertion

### Performance benchmarks
<a name="performance-benchmarks"></a>

When optimizing your AWS Elemental MediaTailor ad insertion CDN integration, aim for these performance benchmarks:

Cache Hit Ratio Targets  
Content segments: greater than 95% cache hit ratio  
Ad segments: greater than 90% cache hit ratio  
Manifests: Not applicable (should not be cached for personalized ad insertion)

Latency Benchmarks  
Manifest request latency: less than 100ms (P95)  
Content segment delivery: less than 50ms (P95)  
Ad segment delivery: less than 75ms (P95)  
End-to-end startup time: less than 2 seconds

Origin Load Metrics  
Origin requests per viewer: less than 0.1 requests per minute per viewer  
Origin bandwidth per viewer: less than 5% of total viewer bandwidth

Error Rate Targets  
Manifest errors: less than 0.1%  
Segment errors: less than 0.01%  
Player-reported rebuffering: less than 1%

Scalability Benchmarks  
Support for 10 times the normal traffic during peak events without degradation  
Ability to handle greater than 1000 requests per second per channel

Use Amazon CloudWatch metrics to track these performance indicators. For detailed monitoring instructions, see [Monitoring AWS Elemental MediaTailor with Amazon CloudWatch metrics](monitoring-cloudwatch-metrics.md).

## Related information
<a name="ssai-cdn-related"></a>

For more information about ad insertion with CDNs, see:

Ad insertion documentation  
[Getting started with MediaTailor ad insertion](getting-started-ad-insertion.md) - Learn about ad insertion concepts  
[Setting up](setting-up.md) - Get started with ad insertion

CDN integration  
[Set up CDN integration](cdn-configuration.md) - General CDN configuration guidance  
[CloudFront integration](cloudfront-specific-recommendations.md) - CloudFront specific configuration

Channel assembly integration  
[Channel assembly with CDN](ca-cdn-wflw.md) - Learn about channel assembly with CDNs  
[Implement ad insertion](ca-cdn-setup-advanced.md) - Implement ad insertion with channel assembly

Monitoring and optimization  
[Monitor operations for CDN and MediaTailor integrations](ssai-cdn-monitor.md) - Comprehensive monitoring and analytics  
[Optimize performance for CDN and MediaTailor integrations](ssai-cdn-performance.md) - Performance optimization guide  
[Monitoring AWS Elemental MediaTailor with Amazon CloudWatch metrics](monitoring-cloudwatch-metrics.md) - CloudWatch metrics for MediaTailor

# Build MediaTailor linear channels with channel assembly and CDN
<a name="ca-cdn-wflw"></a>

This section provides comprehensive guidance for integrating AWS Elemental MediaTailor channel assembly with a content delivery network (CDN). Follow these steps to set up, configure, and optimize your channel assembly CDN integration.

You can also combine channel assembly with server-side ad insertion (SSAI) to create monetized linear channels with personalized advertising. This powerful integration enables you to deliver targeted ads to different viewers watching the same channel content, increasing your revenue opportunities while maintaining a broadcast-quality viewing experience. For information about SSAI with CDNs, see [Ad insertion with CDN](ssai-cdn-workflow.md).

In this topic, we use the term *manifests* to refer collectively to multivariant playlists, media playlists, and MPDs.

For more information about MediaTailor channel assembly, see [Using AWS Elemental MediaTailor to create linear assembled streams](channel-assembly.md). 

## What you'll need
<a name="ca-cdn-what-you-need"></a>

Before setting up MediaTailor channel assembly with a CDN, gather these required resources:

**AWS account and permissions**  
An AWS account with appropriate permissions to create and manage MediaTailor resources  
IAM permissions for MediaTailor, CloudFront (if using), and related services  
For detailed permission requirements, see [Security in AWS Elemental MediaTailor](security.md).

**Required services**  
A running MediaTailor channel assembly channel (not just an SSAI configuration)  
A content delivery network (CDN) account (Amazon CloudFront or third-party CDN)  
Origin storage for your VOD content (Amazon S3, MediaPackage, or other origin server)

**Content requirements**  
VOD sources properly encoded and packaged in HLS or DASH format. For information about working with source locations and VOD sources, see [Working with source locations](channel-assembly-source-locations.md).  
Content with consistent segment durations (recommended minimum: 1 second)  
Ad slate content for ad breaks (if implementing ad insertion). For information about configuring slate, see [MediaTailor slate ad insertion](slate-management.md).

## Before you begin
<a name="ca-cdn-before-you-begin"></a>

**Important**  
This workflow requires a running MediaTailor channel assembly channel. Having only a MediaTailor SSAI configuration is not sufficient for this integration. You must have an active channel assembly channel configured and operational before proceeding with CDN integration.

Complete these setup tasks before implementing MediaTailor channel assembly with a CDN:

1. Configure network connectivity between your CDN, MediaTailor, and origin servers

1. Set up HTTPS for secure content delivery

1. Configure DNS settings for your CDN domain

### Knowledge prerequisites
<a name="ca-cdn-knowledge-prerequisites"></a>

To successfully implement this solution, you should have:
+ Understanding of streaming protocols (HLS/DASH)
+ Basic knowledge of CDN configuration principles
+ Familiarity with MediaTailor channel assembly concepts

For basic MediaTailor setup, refer to [Setting up](setting-up.md) and [Getting started with MediaTailor channel assembly](channel-assembly-getting-started.md). For information about working with source locations and VOD sources, see [Working with source locations](channel-assembly-source-locations.md). For information about configuring slate, see [MediaTailor slate ad insertion](slate-management.md).

## Benefits of CDN integration
<a name="ca-cdn-benefits"></a>

Integrating channel assembly with a CDN delivers these key benefits.

**Improved viewer experience**  
Properly configured CDNs reduce buffering, startup times, and playback errors for linear channels. This results in higher viewer engagement and satisfaction.

**Cost reduction**  
Efficient caching strategies minimize origin requests. This reduces data transfer costs and origin server load, particularly important for high-volume linear channels.

**Scalability**  
Optimized CDN configurations handle traffic spikes during popular events without degrading performance, ensuring your linear channels remain available even during peak viewing times.

**Global reach**  
Properly configured CDNs deliver content with low latency to viewers worldwide, regardless of their location, expanding your potential audience.

**Seamless program transitions**  
Optimized CDN configuration ensures smooth transitions between programs in your linear channel, creating a broadcast-quality viewing experience.

**Topics**
+ [What you'll need](#ca-cdn-what-you-need)
+ [Before you begin](#ca-cdn-before-you-begin)
+ [Benefits of CDN integration](#ca-cdn-benefits)
+ [Understand CDN architecture](channel-assembly-cdn-architecture.md)
+ [Basic setup](ca-cdn-setup-basic.md)
+ [Configure base URLs](channel-assembly-cdn-baseurl.md)
+ [Implement ad insertion](ca-cdn-setup-advanced.md)
+ [Configure time-shifted viewing](channel-assembly-cdn-timeshift.md)
+ [Monitor CDN operations](ca-cdn-monitor.md)
+ [Complete optimization guide](ca-cdn-optimize-reference.md)

# Understand MediaTailor channel assembly CDN architecture
<a name="channel-assembly-cdn-architecture"></a>

AWS Elemental MediaTailor channel assembly integrates with content delivery networks (CDNs) to deliver linear streaming channels with improved performance and global reach. The recommended architecture positions the CDN between viewers and channel assembly, with channel assembly accessing content directly from your origin. This topic explains the core architecture components and how they work together to deliver your content.

1. Viewers request manifests from the CDN

1. CDN forwards requests to channel assembly

1. Channel assembly assembles the manifests from VOD sources

1. Channel assembly returns the manifests to the CDN, which forwards them to viewers

1. Viewers request segments through the CDN

1. CDN routes segment requests to the appropriate origin

This architecture ensures optimal performance while maintaining the security and flexibility benefits of using a CDN.

![\[Diagram showing CDN positioned between client players and MediaTailor Channel Assembly\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/ca-cdn.png)


## CDN terminology for channel assembly
<a name="cdn-terminology"></a>

Understanding these key terms will help you implement and troubleshoot your channel assembly CDN integration:

Origin CDN and edge CDN  
**Origin CDN**: A CDN positioned between MediaTailor and your content origin. It caches content segments to reduce load on your origin servers. In a multi-CDN architecture, this is the first CDN layer that interfaces directly with the origin.  
**Edge CDN**: A CDN positioned between viewers and MediaTailor. It delivers personalized manifests and content to viewers. In a multi-CDN architecture, this is the outermost CDN layer that interfaces directly with viewers.

CDN configuration terms  
**Cache behavior**: Rules that determine how a CDN handles different types of requests, including caching duration and origin routing.  
**TTL (Time To Live)**: The duration for which content remains valid in a CDN cache before it needs to be refreshed from the origin. For detailed TTL recommendations, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).  
**Cache key**: The unique identifier used by a CDN to store and retrieve cached content, often including URL path, query parameters, and headers.  
**Origin shield**: An intermediate caching layer between CDN edge locations and your origin server that reduces the number of requests to your origin.  
**Request collapsing**: A CDN feature that combines multiple simultaneous requests for the same content into a single origin request.

MediaTailor-specific CDN terms  
**CDN content segment prefix**: The CDN domain name that MediaTailor uses when generating URLs for content segments in manifests.  
**CDN ad segment prefix**: The CDN domain name that MediaTailor uses when generating URLs for ad segments in manifests.

For more information about CDN configuration with MediaTailor, see [Set up CDN integration](cdn-configuration.md).

# Set up basic MediaTailor channel assembly with a CDN
<a name="ca-cdn-setup-basic"></a>

AWS Elemental MediaTailor channel assembly enables you to configure a basic integration with your content delivery network (CDN) for efficient delivery of linear streaming channels to your viewers. Follow these steps to set up the integration between channel assembly and your CDN.

1. Configure your CDN to accept manifests from viewers and forward them to MediaTailor channel assembly.

1. Set up MediaTailor channel assembly to access your channel schedule and determine the current programming.

1. Configure MediaTailor channel assembly to request content segments from your origin server based on the schedule.

1. Ensure your content origin can deliver the requested segments to MediaTailor channel assembly.

1. Set up MediaTailor channel assembly to generate dynamic manifests based on the current schedule.

1. Configure your CDN to deliver the assembled multivariant playlists, media playlists, and MPDs to viewers.

1. Set up your CDN to handle segment requests from viewers, with appropriate cache settings.

1. Configure your CDN to forward cache misses to MediaTailor channel assembly.

1. Set up MediaTailor channel assembly to retrieve requested segments from your content origin.

1. Configure your CDN to deliver content segments to viewers for playback.

# Configure base URLs for MediaTailor channel assembly CDN
<a name="channel-assembly-cdn-baseurl"></a>

AWS Elemental MediaTailor channel assembly requires proper base URL configuration to ensure content routing through your content delivery network (CDN) works correctly. Configure the base URL settings in channel assembly to enable successful content delivery to viewers.

## Content segment URL configuration
<a name="channel-assembly-cdn-content-segment"></a>

In your channel assembly channel configuration, set the **Base URL** to your CDN domain. This ensures that all segment URLs in the assembled manifest point to your CDN rather than directly to your origin server.

For example, if your origin content is at `http://origin.example.com/content/` and your CDN domain is `https://cdn.example.com/`, set the Base URL to `https://cdn.example.com/content/`.

## Access restriction configuration
<a name="channel-assembly-cdn-access-restriction"></a>

To enhance security, configure your CDN to restrict direct access to your origin server:

1. Set up origin access controls in your CDN.

1. Configure your origin server to only accept requests from your CDN.

1. Use signed URLs or cookies for viewer authentication if needed.

For Amazon CloudFront, you can use Origin Access Control (OAC) to secure access to your origin. For more information about securing your CloudFront integration, see [CloudFront integration](cloudfront-specific-recommendations.md).

# Implement MediaTailor ad insertion with channel assembly
<a name="ca-cdn-setup-advanced"></a>

Channel assembly in AWS Elemental MediaTailor integrates seamlessly with server-side ad insertion (SSAI) and content delivery networks (CDNs) to create monetized linear channels with personalized advertising.

When you combine channel assembly with SSAI, you can build linear channels that deliver personalized ads to viewers while maintaining broadcast-quality experiences. This integration enables you to do the following:
+ Monetize content - Generate revenue through targeted advertising in your linear channels
+ Personalize experiences - Deliver different ads to viewers watching the same channel based on their profiles
+ Maintain quality - Ensure seamless transitions between content and ads for broadcast-quality viewing
+ Scale efficiently - Support millions of concurrent viewers through CDN delivery

For detailed information about SSAI with CDNs, see [Ad insertion with CDN](ssai-cdn-workflow.md).

1. Configure your edge CDN to accept manifest requests from viewers and forward them to MediaTailor ad insertion.

1. Set up MediaTailor ad insertion to forward requests to your origin CDN.

1. Configure your origin CDN to forward requests to MediaTailor channel assembly.

1. Set up MediaTailor channel assembly to generate dynamic manifests based on the current schedule.

1. Configure your origin CDN to forward the assembled manifests to MediaTailor ad insertion.

1. Set up MediaTailor ad insertion to request ad decisions from your ad decision server at ad break points.

1. Configure MediaTailor ad insertion to personalize manifests with ad markers.

1. Set up your edge CDN to deliver personalized manifests to viewers.

1. Configure your CDN architecture to handle both content and ad segment requests efficiently.

The following diagram illustrates this combined workflow:

![\[Diagram showing CDN integration with both channel assembly and ad insertion\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/ca-ssai-comb-cdn.png)


For optimal performance when combining channel assembly and SSAI:
+ Configure cache behaviors that distinguish between channel assembly and SSAI requests
+ Set appropriate TTL values for manifests and segments as recommended in [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md)
+ Ensure proper routing between channel assembly, ad insertion, and your CDN origins
+ Monitor the performance metrics for both channel assembly and ad insertion components

For detailed information about configuring SSAI with CDNs, see:
+ [Understand ad insertion architecture for CDN and MediaTailor integrations](ssai-cdn-architecture-overview.md) - Learn about SSAI architecture and concepts
+ [Set up basic MediaTailor SSAI with a CDN for optimal ad delivery](configuring-ssai-cdn.md) - Step-by-step SSAI configuration instructions
+ [Troubleshoot MediaTailor SSAI with CDNs for uninterrupted ad delivery](troubleshooting-ssai-cdn.md) - Troubleshoot common SSAI integration issues

# Configure time-shifted viewing for MediaTailor channel assembly
<a name="channel-assembly-cdn-timeshift"></a>

AWS Elemental MediaTailor channel assembly supports time-shifted viewing capabilities that enable DVR-like functionality such as pause, rewind, and start-over for your linear channels. Enable these features by configuring your content delivery network (CDN) to support time-shifted viewing, which allows viewers to control their viewing experience.

## Understanding time-shifted viewing
<a name="channel-assembly-cdn-timeshift-overview"></a>

Time-shifted viewing enables DVR-like functionality for linear channels, including:
+ **Start-over**: Viewers can start watching a program from the beginning, even if they join after it has started
+ **Pause and resume**: Viewers can pause content and resume watching later
+ **Rewind and fast-forward**: Viewers can navigate backward and forward through available content
+ **Delayed viewing**: Viewers can watch content that aired earlier in the channel's schedule

Time-shifted viewing works by adding a `start` parameter to the channel's playback URL. The parameter specifies an offset in seconds relative to the current time:
+ Negative values indicate a time in the past (such as `start=-3600` means "start from 1 hour ago")
+ Positive values indicate a time in the future (such as `start=3600` means "start from 1 hour in the future")

Example URL with time-shift parameter:

```
https://example-cdn.com/out/v1/channel-name/index.m3u8?start=-3600
```

## Time delay resolution
<a name="channel-assembly-cdn-timeshift-delay"></a>

To support time-shifted viewing with a CDN:

1. Configure your CDN to forward the `start` query parameter to channel assembly.

1. Set up cache behaviors that include the `start` parameter in the cache key.

1. For manifests with time-shift parameters, use a short TTL or no caching.

This ensures that each viewer receives the correct manifest for their requested time position.

## CDN requirements for time-shifting
<a name="channel-assembly-cdn-timeshift-requirements"></a>

Your CDN must meet these requirements to support time-shifted viewing with channel assembly:
+ Forward all query parameters to channel assembly.
+ Include the `start` parameter in the cache key.
+ Support proper cache invalidation for time-shifted manifests.
+ Handle varying manifest responses based on query parameters.

# Monitor MediaTailor channel assembly CDN operations
<a name="ca-cdn-monitor"></a>

AWS Elemental MediaTailor channel assembly requires effective monitoring when integrated with a content delivery network (CDN) to ensure reliable content delivery. Implement monitoring strategies for your channel assembly and CDN integration to help ensure reliable content delivery and quick problem resolution.

For comprehensive CDN monitoring guidance including essential metrics, monitoring tools setup, alert configuration, and troubleshooting strategies that apply to all MediaTailor implementations, see [CDN monitoring](cdn-monitoring.md). This section focuses on channel assembly-specific monitoring requirements.

Implement specific monitoring for your channel assembly and CDN integration:
+ Track manifest generation metrics in channel assembly.
+ Monitor time-shifted viewing requests and their impact on CDN cache hit rates.
+ Configure alerts for unusual patterns in manifest requests.
+ Implement tracking for segment availability across your content sources.

For Amazon CloudFront, create a dashboard that integrates CDN metrics with MediaTailor metrics to visualize your entire delivery pipeline using [CloudWatch dashboards](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html).

If you're also using SSAI with your channel assembly, see [Monitor CDN operations](ssai-cdn-monitor.md) for additional monitoring recommendations specific to ad insertion.

# Complete channel assembly CDN optimization
<a name="ca-cdn-optimize-reference"></a>

For detailed CDN optimization guidance specific to channel assembly implementations, including caching strategies, request routing configuration, performance benchmarks, and advanced optimization techniques, see [CDN performance optimization](cdn-optimization.md).

The consolidated optimization guide provides:
+ Channel assembly-specific caching settings with recommended TTL values
+ Request routing optimization for manifest and segment delivery
+ Performance benchmarks and targets for all MediaTailor implementations
+ Advanced optimization techniques including Origin Shield and compression
+ Combined workflow guidance for channel assembly with SSAI

# Integrate MediaTailor with MediaPackage and CDN
<a name="mediapackage-integration"></a>

AWS Elemental MediaTailor integrates with AWS Elemental MediaPackage to deliver personalized video ads through a content delivery network (CDN). MediaPackage is a just-in-time video packaging and origination service that prepares and protects your video content for delivery over the internet. It takes your live or on-demand video content and packages it into streaming formats like HLS and DASH, making it ready for viewers on various devices.

When you combine MediaPackage with MediaTailor and a CDN, you create a complete streaming workflow that delivers personalized ads at scale. The CDN distributes your content globally, reducing latency and improving viewer experience, while MediaTailor inserts targeted advertisements into your streams.

This topic focuses on the essential integration steps to get MediaTailor, MediaPackage, and your CDN working together. For advanced configuration options, troubleshooting, and monitoring guidance, see [Next steps](#emp-cdn-next-steps).

## Understanding the MediaPackage and CDN workflow
<a name="emp-cdn-overview"></a>

Before configuring your integration, it's important to understand how MediaPackage, MediaTailor, and your CDN work together:

1. **Content preparation**: MediaPackage receives your live or on-demand video content and packages it into streaming formats (HLS or DASH manifests and segments).

1. **Ad insertion**: MediaTailor requests manifests from MediaPackage, inserts personalized ads, and serves the modified manifests to viewers.

1. **Global distribution**: Your CDN caches and distributes both the content segments (from MediaPackage) and ad segments (from MediaTailor) to viewers worldwide.

1. **Viewer playback**: Video players request manifests through the CDN, which routes requests appropriately between MediaTailor (for manifests) and MediaPackage (for content segments).

This architecture provides several benefits:
+ **Scalability**: The CDN handles high viewer loads without impacting your origin servers
+ **Performance**: Content is delivered from edge locations closest to viewers
+ **Cost efficiency**: Reduced bandwidth costs through caching
+ **Reliability**: Multiple edge locations provide redundancy

## Prerequisites
<a name="emp-cdn-prerequisites"></a>

Before you begin, ensure you have the following components configured:

1. **MediaPackage endpoint**: A configured MediaPackage endpoint that's receiving and packaging your video content. For setup instructions, see [Getting started with MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/ug/getting-started.html) in the MediaPackage user guide.

1. **MediaTailor configuration**: A MediaTailor configuration that uses your MediaPackage endpoint as the content origin. For setup instructions, see [Integrating a content source for MediaTailor ad insertion](integrating-origin.md).

1. **CDN distribution**: A CDN distribution (such as CloudFront) configured to work with streaming media. For setup instructions, see [Creating a distribution](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html) in the CloudFront developer guide.

1. **Ad decision server**: A configured ad decision server that returns VAST or VMAP responses for ad insertion.

## Step 1: Configure essential CDN settings
<a name="mediapackage-best-practices"></a>

Proper CDN configuration is critical for successful MediaPackage integration. Incorrect settings can cause playback failures, poor cache performance, and increased costs. Without the right cache policies and query parameter forwarding, your CDN might not deliver manifests correctly or might bypass caching entirely, leading to high origin server load and degraded viewer experience.

### Configure basic cache settings
<a name="mediapackage-cache-control"></a>

Configuring basic caching is essential because MediaPackage uses specific cache-control headers to optimize content delivery. Without proper cache settings, your CDN might ignore these headers, leading to unnecessary origin requests and increased latency. Follow these steps to ensure optimal caching behavior:

To configure basic caching that works with MediaPackage:

1. Open your CloudFront distribution settings in the CloudFront console.

1. Select or create a cache policy for your MediaPackage origin.

1. Enable the "Origin Cache-Control Headers" option.

1. Allow MediaPackage to control caching behavior through its cache-control headers.

This basic configuration allows MediaPackage to set appropriate cache durations for different content types automatically. To implement advanced cache optimization with specific TTL values and performance tuning, complete this basic setup first, then continue to [Optimize CDN caching for MediaTailor and MediaPackage content delivery](cdn-emp-caching.md).

### Configure essential query parameters
<a name="mediapackage-query-strings"></a>

Query parameter configuration is crucial for MediaPackage functionality. Your CDN must forward specific query parameters to enable features like time-shifted viewing and low-latency streaming. Incorrect query parameter settings can prevent these features from working and I'm concerned reduce cache efficiency. Follow these steps to configure query parameter forwarding:

To ensure your CDN forwards the required query parameters to MediaPackage:

1. In your CloudFront distribution settings, select or create a cache policy for manifest requests.

1. Under "Cache key settings," select "Include specified query strings."

1. Add the following essential query parameters:
   + `start` and `end` - For time-shifted viewing functionality. These parameters are passed through to MediaPackage to define specific content windows for startover and catch-up viewing
   + `_HLS_msn` and `_HLS_part` - For supporting LL-HLS playback requests
   + `m` - For capturing the modified ti/compame of the endpoint. MediaPackage responses always include the `?m=###` tag to capture the modified time of the endpoint. If content is already cached with a different value for this tag, CloudFront requests a new manifest instead of serving the cached version
   + `aws.manifestfilter` - For manifest filtering functionality. If you're using manifest filtering, this parameter must be included to configure the distribution to forward the `aws.manifestfilter` query string to the MediaPackage origin, which is required for the manifest filtering feature to work

1. Only include the query strings that MediaPackage uses. Including unnecessary query strings reduces cache efficiency by creating multiple cache variations for the same content.

These parameters enable basic MediaPackage functionality with your CDN. If you need to implement content filtering for different subscription tiers or device types, complete this basic query parameter setup first, then proceed to [Set up manifest filtering with MediaTailor, MediaPackage, and CDN](cdn-emp-manifest-filtering.md).

For information about how MediaTailor passes query parameters like `start` and `end` through to MediaPackage for time-shifted viewing, see [MediaTailor query parameter handling for origins](origin-query-parameters.md) in [MediaTailor manifest query parameters](manifest-query-parameters.md).

### Configure response timeout for LL-HLS
<a name="mediapackage-response-timeout"></a>

Timeout configuration is critical for low-latency HLS because LL-HLS uses a "blocking requests" mechanism where the CDN waits for new content segments. If your timeout is too short, requests will fail before MediaPackage can respond with new segments, causing playback interruptions and poor viewer experience. Configure appropriate timeouts to ensure smooth LL-HLS playback:

If you're using low-latency HLS, configure your CDN timeout settings:

1. In your CDN settings, locate the origin timeout configuration.

1. Set the response timeout value to at least three times your parts duration.

1. For example, if your parts duration is 0.3 seconds, set the timeout to at least 0.9 seconds.

This ensures the CDN waits long enough for MediaPackage to respond when using the Blocking Requests mechanism.

## Step 2: Verify your integration
<a name="manifest-filtering-integration"></a>

Testing your integration is essential to ensure that all components work together correctly before your viewers experience issues. A failed integration can result in broken playback, missing ads, or poor performance. This verification process helps you identify and resolve issues in a controlled environment.

After configuring your CDN settings, verify that your integration is working correctly by testing the complete workflow from content request to ad insertion.

### Step 2.1: Test basic playback
<a name="manifest-filtering-overview"></a>

Basic playback testing verifies that your CDN correctly handles manifest requests and forwards them to MediaTailor. This test helps identify configuration issues with cache policies, query parameter forwarding, and manifest handling. Follow these steps to test basic manifest delivery:

Test that your basic integration is working by requesting a manifest through your CDN:

1. Use a web browser or curl to request a manifest URL through your CDN.

1. Verify that the manifest loads successfully and contains both content and ad segments.

1. Check that content segment URLs in the manifest point to your CDN domain.

1. Confirm that ad segment URLs also point to your CDN domain.

If the manifest loads correctly and contains the expected URLs, your basic integration is working. For comprehensive testing methodologies and advanced validation procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md). To set up comprehensive monitoring of your integration's performance and health, see [Monitor performance for MediaPackage, CDN, and MediaTailor integrations](cdn-emp-monitoring.md).

### Step 2.2: Test video playback
<a name="manifest-filtering-cdn-config"></a>

Video playback testing ensures that your complete integration works end-to-end, including ad insertion and content delivery through your CDN. This test verifies that both content segments and ad segments are properly cached and delivered, and that the viewer experience meets your quality standards. Follow these steps to test complete playback functionality:

Test that video playback works correctly with ads inserted:

1. Use a video player (such as Video.js or HLS.js) to play your content through the CDN.

1. Verify that the video plays smoothly without buffering issues.

1. Confirm that ads are inserted at the expected times during playback.

1. Check that both content and ad segments load from your CDN (not directly from origins).

If playback works smoothly with ads, your integration is functioning correctly. For comprehensive testing methodologies and advanced validation procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md). If you experience any playback issues, buffering, or ad insertion problems, see [Troubleshoot MediaPackage, CDN, and MediaTailor integrations](cdn-emp-troubleshooting.md).

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

After completing the basic integration, you can implement advanced features and optimizations:

**Advanced CDN optimization**  
For detailed cache optimization, TTL configuration, and performance tuning, see [Optimize CDN caching for MediaTailor and MediaPackage content delivery](cdn-emp-caching.md).

**Manifest filtering**  
To implement content filtering for tiered services, device optimization, or access control, see [Set up manifest filtering with MediaTailor, MediaPackage, and CDN](cdn-emp-manifest-filtering.md).

**Troubleshooting**  
If you encounter issues with your integration, see [Troubleshoot MediaPackage, CDN, and MediaTailor integrations](cdn-emp-troubleshooting.md).

**Performance monitoring**  
To set up comprehensive monitoring and understand key performance metrics, see [Monitor performance for MediaPackage, CDN, and MediaTailor integrations](cdn-emp-monitoring.md).

# Set up manifest filtering with MediaTailor, MediaPackage, and CDN
<a name="cdn-emp-manifest-filtering"></a>

AWS Elemental MediaTailor uses manifest filtering with AWS Elemental MediaPackage to customize which audio and video streams are included in manifests delivered to different viewers through a content delivery network (CDN). This is particularly useful for implementing tiered service offerings, device-specific optimizations, or content access controls.

This topic focuses specifically on implementing manifest filtering features. Before implementing manifest filtering, you must complete the basic content delivery network integration setup. If you haven't set up your basic MediaPackage and content delivery network integration yet, start with [Integrate MediaTailor with MediaPackage and CDN](mediapackage-integration.md).

## Manifest filtering capabilities
<a name="manifest-filtering-overview"></a>

Before implementing manifest filtering, understand what you can accomplish with this feature:

### Core filtering capabilities
<a name="filtering-capabilities"></a>

Manifest filtering provides several key capabilities that help you control content delivery:
+ Restrict viewer access to premium content (such as 4K HEVC)
+ Target specific device types with appropriate streams
+ Filter content based on audio sample rates, languages, or video codecs
+ Deliver different quality tiers to different subscribers

### Common use cases
<a name="filtering-use-cases"></a>

These use cases demonstrate how manifest filtering can address specific business requirements:

**Subscription tiers**  
Offer basic subscribers lower resolution streams while providing premium subscribers access to 4K content  
Example: Basic tier limited to 720p, Premium tier gets up to 4K

**Device optimization**  
Automatically serve appropriate streams based on device capabilities  
Example: Mobile devices get lower bitrates, smart TVs get higher quality

**Bandwidth management**  
Limit stream quality during peak usage periods to manage network costs  
Example: Reduce maximum bitrate during high-traffic events

**Regional content**  
Serve different audio languages or content variants based on viewer location  
Example: Automatically filter for local language audio tracks

For more information about manifest filtering concepts, see [Manifest filtering](https://docs.aws.amazon.com/mediapackage/latest/ug/manifest-filtering.html) in the AWS Elemental MediaPackage user guide.

## Configure your CDN for manifest filtering
<a name="cdn-filtering-configuration"></a>

CDN configuration for manifest filtering is essential because your CDN must forward the `aws.manifestfilter` query parameter to MediaPackage for filtering to work. Without proper query string forwarding, filter parameters will be stripped by the CDN, and all viewers will receive unfiltered manifests regardless of their subscription tier or device capabilities. This configuration ensures that your filtering logic reaches MediaPackage and functions as intended.

To enable manifest filtering through your CDN, you need to configure query string forwarding:

1. In your CloudFront distribution, create or edit the cache behavior for manifest requests.

1. For **Cache policy,** create a new policy or edit an existing one.

1. Under **Cache key settings**, choose "Include specified query strings."

1. Add `aws.manifestfilter` to the list of allowed query strings.

1. If you're also using other MediaPackage features, add their query parameters:
   + `start` and `end` - For time-shifted viewing
   + `time_delay` - For time delay functionality
   + `_HLS_msn` and `_HLS_part` - For LL-HLS

For more information about creating distributions, see [Create a distribution](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html) in the Amazon CloudFront developer guide.

## Implement client-side filtering
<a name="client-side-filtering-implementation"></a>

Client-side implementation is where you define how your video players and applications request filtered content. This configuration determines what content each viewer receives based on their subscription level, device capabilities, or other criteria. Proper implementation ensures that viewers receive only the content they should have access to, while maintaining optimal CDN cache efficiency.

To implement manifest filtering in your video players and applications:

### How filtering works
<a name="filtering-workflow"></a>

The filtering process works as follows:

1. Your video player or application requests a manifest URL that includes filter parameters

1. The CDN forwards the request (including query parameters) to MediaTailor

1. MediaTailor passes the filter parameters to MediaPackage when requesting the origin manifest

1. MediaPackage applies the filters and returns a customized manifest containing only the variants that match your criteria

1. MediaTailor processes the filtered manifest for ad insertion and returns it to the player

### URL format for filtering
<a name="filtering-url-format"></a>

Understanding the correct URL format is critical for successful filtering implementation. Incorrect URL formatting will result in filtering parameters being ignored or causing HTTP errors. The URL structure must include filter parameters as query strings that your CDN forwards to MediaPackage. Follow these steps to implement proper URL formatting:

To implement manifest filtering in your video players:

1. Modify your player's manifest request URLs to include the appropriate filter parameters.

1. Use the following URL format with query parameters:

   ```
   https://CloudFront-Domain/v1/master/MediaTailor-Config/index.m3u8?aws.manifestfilter=video_codec:h264;audio_language:en-US
   ```

1. When your player requests this URL, MediaTailor will pass these parameters to MediaPackage, resulting in a filtered manifest.

## Common filtering scenarios
<a name="filtering-examples"></a>

Use these examples to implement common filtering scenarios:

**Device-specific content delivery**  
To filter based on device capabilities, add this parameter to your manifest request:  

```
aws.manifestfilter=video_codec:h264;audio_sample_rate:0-44100
```
This example limits content to H.264 video and audio with sample rates up to 44.1 kHz, suitable for mobile devices.

**Premium content restriction**  
To limit access to high-bitrate content, add this parameter to your manifest request:  

```
aws.manifestfilter=video_bitrate:0-9000000
```
This example restricts video bitrates to 9 Mbps or lower, suitable for basic subscription tiers.

**Language selection**  
To filter for specific audio languages, add this parameter to your manifest request:  

```
aws.manifestfilter=audio_language:fr,en-US,de
```
This example includes only French, US English, and German audio tracks.

**Resolution targeting**  
To filter for specific video resolutions, add this parameter to your manifest request:  

```
aws.manifestfilter=video_height:240-360,720-1080
```
This example includes video streams with heights between 240-360 pixels and 720-1080 pixels, excluding mid-range resolutions.

**Codec-based filtering**  
To filter for specific video codecs, add this parameter to your manifest request:  

```
aws.manifestfilter=video_codec:h264,h265
```
This example includes only H.264 and H.265 video streams, excluding other codecs.

## Special considerations and limitations
<a name="filtering-considerations"></a>

To avoid common issues when implementing manifest filtering:

### Technical limitations
<a name="technical-limitations"></a>
+ For TS manifests, use audio rendition groups to avoid removing video streams that are multiplexed with filtered-out audio streams
+ In TS and CMAF manifests, audio sample rate and video bitrate are not easily visible in the manifest for verification
+ Request parameters appended to media playlists or segments will result in an HTTP 400 error

### Error conditions
<a name="error-conditions"></a>
+ If filtering results in an empty manifest (no streams meet the filter criteria), MediaPackage will return an HTTP 400 error
+ Conflicting filter configurations (endpoint filters \$1 query parameters) result in HTTP 404 errors
+ Invalid filter syntax or unsupported filter types result in HTTP 400 errors

### Performance considerations
<a name="performance-considerations"></a>
+ Each unique filter combination creates a separate cache entry, potentially reducing cache efficiency
+ Complex filters with many criteria might impact manifest generation performance
+ Consider using endpoint-level filters for static filtering scenarios to improve cache performance

## Test your filtering implementation
<a name="filtering-testing"></a>

Testing your manifest filtering implementation is crucial to ensure that viewers receive the correct content based on their access level and device capabilities. Failed filtering can result in viewers receiving incorrect quality levels, unsupported formats, or content they shouldn't have access to. Comprehensive testing helps identify and resolve these issues before they affect your viewers.

To verify that your manifest filtering is working correctly:

1. Request manifests with different filter parameters and verify the results

1. Check that filtered manifests contain only the expected streams

1. Test edge cases (empty results, invalid filters) to ensure proper error handling

1. Verify that your CDN is properly forwarding filter parameters

1. Test with different devices and players to ensure compatibility

For troubleshooting filtering issues, see *Troubleshoot MediaPackage CDN integration issues*.

If you encounter HTTP 400 errors, empty manifests, or filtering parameters that don't work as expected, see [Troubleshoot MediaPackage, CDN, and MediaTailor integrations](cdn-emp-troubleshooting.md) for specific manifest filtering troubleshooting guidance.

# Optimize CDN caching for MediaTailor and MediaPackage content delivery
<a name="cdn-emp-caching"></a>

AWS Elemental MediaTailor requires proper content delivery network (CDN) caching configuration for optimal performance when using AWS Elemental MediaPackage as your content origin. MediaPackage provides specific cache-control headers that tell your content delivery network how long to cache different types of content. Following these recommendations ensures smooth playback and efficient content delivery.

This topic focuses specifically on optimizing caching behavior to maximize performance and minimize costs. Before implementing advanced caching optimization, ensure you have completed the basic content delivery network integration setup. If you haven't set up your basic integration yet, start with [Integrate MediaTailor with MediaPackage and CDN](mediapackage-integration.md).

## MediaPackage cache-control headers
<a name="emp-cache-control-headers"></a>

MediaPackage sets specific TTL values for different content types to optimize caching behavior:

**Multivariant playlists (HLS and LL-HLS)**  
TTL: Half the duration of the media segments  
Reason: These playlists change as new segments become available, so they need frequent updates

**Media playlists (regular HLS)**  
TTL: Half the duration of the media segments  
Reason: Similar to multivariant playlists, these update as content progresses

**Media playlists (LL-HLS)**  
TTL: 1 second  
Reason: Low-latency streaming requires very frequent updates

**TS media segments and init segments**  
TTL: 1209600 seconds (14 days)  
Reason: Media segments don't change once created, so they can be cached for extended periods

**CMAF media segments and initialization segments**  
TTL: 1209600 seconds (14 days)  
Reason: Like TS segments, these are immutable once created

For comprehensive TTL recommendations across all MediaTailor workflows and additional caching optimization strategies, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

## Configure CDN cache policies
<a name="cdn-cache-policy-configuration"></a>

Proper cache policy configuration is essential for optimal performance and cost efficiency. Different types of content (manifests, segments, initialization files) have different caching requirements. Using separate cache behaviors allows you to optimize caching for each content type, improving cache hit ratios and reducing origin load. Without proper cache policies, you might experience unnecessary origin requests, increased costs, and poor playback performance.

To properly honor MediaPackage cache-control headers and optimize caching:

1. Open your CloudFront distribution settings in the CloudFront console.

1. Create separate cache behaviors for different content types:
   + Manifest requests (\$1.m3u8, \$1.mpd)
   + Media segments (\$1.ts, \$1.mp4, \$1.m4s)
   + Initialization segments

1. For each cache behavior, create or select a cache policy with these settings:
   + Enable "Origin Cache-Control Headers" option
   + Set "Origin request policy" to forward necessary headers
   + Configure query string forwarding based on content type

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

For manifest requests (\$1.m3u8, \$1.mpd):
+ **Path pattern**: \$1.m3u8 and \$1.mpd
+ **Cache policy**: Honor origin cache-control headers
+ **Query strings**: Forward specific parameters (see [Optimize query string forwarding](#cdn-query-string-optimization))
+ **Headers**: Forward all headers (for minimum requirements, see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers))

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

For media segments (\$1.ts, \$1.mp4, \$1.m4s):
+ **Path pattern**: \$1.ts, \$1.mp4, \$1.m4s
+ **Cache policy**: Honor origin cache-control headers (14-day TTL)
+ **Query strings**: None (segments don't use query parameters)
+ **Compression**: Enable for improved delivery performance

## Optimize query string forwarding
<a name="cdn-query-string-optimization"></a>

Query string optimization is critical for cache efficiency because unnecessary query parameters create multiple cache variations for the same content. Each unique query parameter combination creates a separate cache entry, which reduces cache hit ratios and increases origin requests. By forwarding only the query strings that MediaPackage actually uses, you maximize cache efficiency while maintaining full functionality.

Configure your CDN to forward only the query strings that MediaPackage uses, improving cache efficiency:

**Essential query strings**  
`start` and `end` - For time-shifted viewing windows  
`time_delay` - For applying time delay on manifest contents  
`_HLS_msn`, `_HLS_m`, and `_HLS_part` - For LL-HLS playback requests

**Feature-specific query strings**  
`aws.manifestfilter` - For [manifest filtering](cdn-emp-manifest-filtering.md)

**Important**  
Do not include any other query strings in your cache key. MediaPackage ignores unrecognized parameters, and including them reduces cache efficiency by creating unnecessary cache variations.

## Performance optimization techniques
<a name="cache-performance-optimization"></a>

These optimizations are configured on your CDN (such as CloudFront), not in MediaPackage or MediaTailor. Implement these additional optimizations to maximize cache performance:

### Origin shield
<a name="origin-shield-configuration"></a>

Origin shield provides an additional caching layer between your CDN edge locations and MediaPackage endpoints. This reduces the number of requests that reach your MediaPackage endpoints, which can improve performance and reduce costs, especially during traffic spikes or when cache hit ratios are lower than optimal. Origin shield is particularly beneficial for live streaming where multiple edge locations might request the same content simultaneously.

Enable origin shield to reduce load on your MediaPackage endpoints:

1. In your CloudFront distribution, enable Origin Shield for your MediaPackage origin.

1. Select an origin shield region close to your MediaPackage endpoint.

1. This creates an additional caching layer that reduces requests to MediaPackage.

### Compression configuration
<a name="compression-settings"></a>

Enable compression for text-based responses:
+ Enable compression for manifest files (\$1.m3u8, \$1.mpd)
+ Do not compress media segments (already compressed)
+ Ensure all headers are forwarded to MediaPackage (for minimum requirements, see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers))

## Monitor cache performance
<a name="cache-monitoring-metrics"></a>

Track these key metrics to ensure optimal cache performance:

**Cache hit ratio**  
Target: 90% or greater for media segments, 70% or greater for manifests  
Low ratios might indicate incorrect TTL settings or unnecessary query parameters

**Origin request volume**  
Monitor requests reaching MediaPackage endpoints  
High volumes might indicate caching issues

**Cache key variations**  
Review cache key patterns to identify unnecessary variations  
Too many variations reduce cache efficiency

After implementing these cache optimizations, set up monitoring to track their effectiveness. For guidance on monitoring cache hit ratios, origin request patterns, and other key performance metrics, see [Monitor performance for MediaPackage, CDN, and MediaTailor integrations](cdn-emp-monitoring.md). If you observe poor cache performance or unexpected origin requests, see [Troubleshoot MediaPackage, CDN, and MediaTailor integrations](cdn-emp-troubleshooting.md) for troubleshooting steps.

# Monitor performance for MediaPackage, CDN, and MediaTailor integrations
<a name="cdn-emp-monitoring"></a>

AWS Elemental MediaTailor requires effective monitoring to maintain optimal performance of your AWS Elemental MediaPackage and content delivery network (CDN) integration. This topic provides guidance on key metrics to track, monitoring tools to use, and how to set up alerts for proactive issue detection.

Before setting up monitoring, ensure your basic integration is working correctly. If you haven't completed your basic content delivery network integration setup, start with [Integrate MediaTailor with MediaPackage and CDN](mediapackage-integration.md). If you need to troubleshoot issues identified through monitoring, see [CDN integration troubleshooting](cdn-emp-troubleshooting.md)..

## Key performance metrics
<a name="key-performance-metrics"></a>

Monitor these essential metrics to ensure optimal performance of your MediaPackage and CDN integration:

### CDN performance metrics
<a name="cdn-metrics"></a>

For comprehensive CDN performance metrics including cache hit ratio targets, origin request volume monitoring, and response time benchmarks, see [Performance benchmarks for CDN and MediaTailor integrations](cdn-performance-benchmarks.md) in the CDN optimization guide.

Key EMP-specific considerations for CDN metrics:

**EMP cache-control headers**  
**What to verify**: Ensure your CDN honors EMP's cache-control headers for optimal TTL behavior  
**Expected behavior**: Different content types should have different cache durations based on EMP's headers  
For detailed guidance on EMP cache optimization, see [Optimize CDN caching for MediaTailor and MediaPackage content delivery](cdn-emp-caching.md).

**Query parameter impact**  
**What to monitor**: Track how EMP-specific query parameters affect cache efficiency  
**Optimization target**: Ensure only necessary EMP query parameters are included in cache keys

**CDN response times**  
**What to monitor**: Track response times for different content types (manifests vs. segments).  
**Target values**:  
+ Cached content: less than 100ms
+ Origin requests: less than 500ms

### MediaPackage performance metrics
<a name="emp-metrics"></a>

**Error rates**  
**What to monitor**: Monitor HTTP error rates from both your CDN and MediaPackage endpoints. Pay particular attention to 4xx errors, which might indicate configuration issues.  
**Key error codes**:  
+ 400 errors: Often related to manifest filtering issues
+ 404 errors: Might indicate routing or configuration problems
+ 504 errors: Timeout issues, especially with LL-HLS

**Request volume and patterns**  
**What to monitor**: Track request patterns to MediaPackage endpoints to identify usage trends and capacity needs.  
**Patterns to watch**:  
+ Peak usage times
+ Geographic distribution of requests
+ Content type distribution (live vs. on-demand)

### Latency metrics
<a name="latency-metrics"></a>

**End-to-end latency**  
**What to monitor**: For LL-HLS implementations, monitor end-to-end latency from content ingest to viewer playback. High latency might indicate CDN configuration issues.  
**Target values**:  
+ LL-HLS: less than 3 seconds glass-to-glass latency
+ Regular HLS: less than 30 seconds

**Manifest generation time**  
**What to monitor**: Time taken by MediaPackage to generate manifests, especially with filtering applied.  
**Target values**: less than 200ms for manifest generation

## Monitoring tools and setup
<a name="monitoring-tools"></a>

Setting up comprehensive monitoring tools is essential for maintaining optimal performance and quickly identifying issues before they impact viewers. Without proper monitoring, performance degradation, cache inefficiencies, or integration problems might go unnoticed until viewers experience poor playback quality. The right monitoring setup provides visibility into all aspects of your MediaPackage and CDN integration.

Use these AWS services and tools to monitor your MediaPackage and CDN integration:

### Amazon CloudWatch
<a name="cloudwatch-monitoring"></a>

Amazon CloudWatch provides the foundation for monitoring your MediaPackage and CDN integration by collecting and storing metrics from both services. Proper CloudWatch configuration ensures you have the data needed to identify performance trends, troubleshoot issues, and optimize your integration. Without CloudWatch metrics, you'll lack visibility into system performance and might not detect issues until they become critical.

Set up CloudWatch monitoring for comprehensive metrics collection:

1. **MediaPackage metrics**: Enable CloudWatch metrics for your MediaPackage endpoints to track request volumes, error rates, and response times.

1. **CDN metrics**: Configure CloudWatch to collect CloudFront metrics including cache hit ratios, origin request counts, and error rates.

1. **Custom metrics**: Create custom metrics for business-specific KPIs like viewer engagement or content popularity.

### CloudWatch dashboards
<a name="dashboard-setup"></a>

Create comprehensive dashboards to visualize your metrics:

1. **Overview dashboard**: High-level metrics showing overall system health

1. **CDN performance dashboard**: Detailed CDN metrics including cache performance and geographic distribution

1. **MediaPackage performance dashboard**: MediaPackage-specific metrics including request patterns and error rates

1. **Latency dashboard**: End-to-end latency metrics for different content types and regions

### Log analysis
<a name="log-analysis"></a>

Set up log analysis for detailed troubleshooting:

1. **CDN access logs**: Enable and analyze CDN access logs to understand request patterns and identify issues

1. **MediaPackage CloudWatch logs**: Monitor MediaPackage logs for errors and performance issues

1. **Log aggregation**: Use Amazon CloudWatch Logs Insights or third-party tools to analyze log patterns

## Set up alerts and notifications
<a name="alerting-setup"></a>

Alert configuration is crucial for proactive issue detection and resolution. Without proper alerts, issues might go unnoticed until they significantly impact viewer experience or cause service disruptions. Well-configured alerts help you identify and address problems before they affect your viewers, and ensure your team is notified of critical issues that require immediate attention.

Configure proactive alerts to identify issues before they impact viewers:

### Critical alerts
<a name="critical-alerts"></a>

Set up immediate alerts for critical issues:
+ **High error rates**: Alert when 4xx or 5xx error rates exceed 5% over a 5-minute period
+ **Cache hit ratio drops**: Alert when cache hit ratio falls below 70% for manifests or 85% for segments
+ **High latency**: Alert when end-to-end latency exceeds target thresholds
+ **Origin request spikes**: Alert when origin requests increase by more than 50% compared to baseline

### Warning alerts
<a name="warning-alerts"></a>

Set up warning alerts for trends that might indicate developing issues:
+ **Gradual performance degradation**: Alert when response times increase by 20% over a 30-minute period
+ **Cache efficiency trends**: Alert when cache hit ratios show declining trends over time
+ **Unusual traffic patterns**: Alert for unexpected changes in request volume or geographic distribution

## Use monitoring data for optimization
<a name="performance-optimization"></a>

Leverage monitoring data to continuously improve performance:

### Regular performance reviews
<a name="regular-reviews"></a>

1. **Weekly reviews**: Analyze weekly performance trends and identify optimization opportunities

1. **Monthly capacity planning**: Use traffic patterns to plan for capacity needs and CDN optimization

1. **Quarterly architecture reviews**: Evaluate overall architecture efficiency and identify areas for improvement

### Common optimization actions
<a name="optimization-actions"></a>

Based on monitoring data, consider these optimization actions:
+ **Cache policy adjustments**: Modify TTL values based on actual content update patterns. For detailed TTL optimization guidance, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).
+ **Geographic optimization**: Add CDN edge locations in regions with high traffic
+ **Query parameter optimization**: Remove unnecessary query parameters that fragment cache
+ **Origin shield configuration**: Implement origin shield in regions with high origin request volumes

For detailed monitoring guidance specific to MediaPackage, see [Monitoring MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/ug/monitoring.html) in the MediaPackage user guide.

# Troubleshoot MediaPackage, CDN, and MediaTailor integrations
<a name="cdn-emp-troubleshooting"></a>

AWS Elemental MediaTailor integration with AWS Elemental MediaPackage and content delivery network (CDN) can encounter common issues that affect playback, caching, or other integration functionality. Use this guide when you encounter playback problems, caching issues, or other integration-related errors.

For comprehensive CDN troubleshooting guidance including universal cache performance issues, HTTP error resolution, testing procedures, and diagnostic techniques that apply to all MediaTailor implementations, see [Troubleshoot CDN integration](cdn-troubleshooting.md). This section focuses on MediaPackage specific troubleshooting requirements.

Before troubleshooting, ensure you've completed the basic integration setup correctly. If you haven't set up your integration yet or need to review the setup steps, see [Integrate MediaTailor with MediaPackage and CDN](mediapackage-integration.md). For guidance on optimizing cache performance after resolving issues, see [CDN caching](cdn-emp-caching.md).

## Manifest filtering errors
<a name="manifest-filtering-errors"></a>

Issues with MediaPackage manifest filtering functionality, based on documented error conditions:

**HTTP 400 errors with manifest filtering**  
**Symptoms**: Requests with `aws.manifestfilter` parameters return HTTP 400 Bad Request  
**Validated causes (from AWS documentation)**:  
+ Filter criteria result in an empty manifest (no streams match the filter conditions)
+ Invalid filter parameter names or values
+ Malformed query string syntax
+ Duplicate or repeated filter parameters
+ Filter parameter string exceeds 1024 characters
+ Query parameters applied to media playlists or segments (not supported)
**Solutions**:  

1. Review your filter parameters to ensure they match available content streams. If filtering results in no matching streams, MediaPackage returns HTTP 400.

1. Validate filter syntax against supported parameter names and value formats.

1. Check for duplicate parameters in your query string.

1. Ensure filter parameters are only applied to multivariant playlists, not to media playlists or segments.

1. Verify that your total parameter string is under 1024 characters.
**Reference**: [AWS Elemental MediaPackage manifest filtering error conditions](https://docs.aws.amazon.com/mediapackage/latest/userguide/error-conditions-and-handling.html)

**Manifest filtering not working (HTTP 200 but no filtering applied)**  
**Symptoms**: Requests return HTTP 200 but manifest contains all streams instead of filtered subset  
**Possible causes**:  
+ CDN not forwarding `aws.manifestfilter` query parameter to MediaPackage
+ Filter parameter not found in available streams (returns unfiltered manifest with HTTP 200)
**Solutions**:  

1. Verify that your CDN cache policy includes `aws.manifestfilter` in the list of forwarded query strings.

1. Test filter parameters directly against MediaPackage endpoints (bypassing CDN) to verify they work as expected.

1. Check that filter values match the actual characteristics of your content streams.
**Reference**: [AWS Elemental MediaPackage manifest filtering error conditions](https://docs.aws.amazon.com/mediapackage/latest/userguide/error-conditions-and-handling.html)

## Diagnostic procedures
<a name="validated-diagnostic-steps"></a>

Systematic diagnostic procedures help you identify the root cause of integration issues quickly and efficiently. Following a structured approach prevents wasted time on incorrect assumptions and ensures you address the actual problem rather than symptoms. These evidence-based diagnostic steps are designed to isolate issues and guide you to the appropriate solution.

Follow these evidence-based diagnostic steps to identify issues:

### Analyze cache performance
<a name="cache-performance-analysis"></a>

Cache performance analysis is crucial for EMP integrations because poor cache efficiency leads to increased origin load, higher costs, and potential playback issues.

For comprehensive cache performance troubleshooting including cache hit ratio analysis, cache key optimization, and systematic diagnostic steps, see [CDN cache performance issues](diagnose-performance-issues.md#cache-performance-troubleshooting) in the main CDN troubleshooting guide.

EMP-specific cache considerations:
+ **EMP cache-control headers**: Verify that your CDN honors EMP's cache-control headers rather than overriding them
+ **EMP query parameters**: Ensure only necessary EMP query parameters are included in cache keys
+ **EMP TTL behavior**: Confirm different EMP content types have appropriate cache durations

For detailed guidance on optimizing EMP cache policies and TTL settings, see [Optimize CDN caching for MediaTailor and MediaPackage content delivery](cdn-emp-caching.md).

### Validate manifest filtering configuration
<a name="manifest-filtering-validation"></a>

Manifest filtering validation is essential because filtering issues can result in viewers receiving incorrect content, unsupported formats, or content they shouldn't have access to. Systematic testing helps identify whether issues are related to CDN configuration, filter parameter syntax, or content availability.

Test manifest filtering functionality systematically:

1. Test filter parameters directly against MediaPackage endpoints (bypassing CDN) to verify they work correctly.

1. Compare filtered and unfiltered manifests to confirm expected streams are included/excluded.

1. Verify that your CDN cache policy forwards the `aws.manifestfilter` query parameter.

1. Check for HTTP 400 errors and match them against the documented error conditions.

If you need to implement or modify manifest filtering after resolving issues, see [Set up manifest filtering with MediaTailor, MediaPackage, and CDN](cdn-emp-manifest-filtering.md) for complete setup guidance.

### Validate query parameter configuration
<a name="query-parameter-validation"></a>

Ensure your CDN forwards only the required query parameters:

1. Review your CDN cache policy to confirm it includes only AWS recommended parameters:
   + `aws.manifestfilter` - for manifest filtering
   + `aws.manifestsettings` - for time-shifted viewing
   + `_HLS_msn` and `_HLS_part` - for LL-HLS support

1. Remove any other query parameters from your cache key, as MediaPackage ignores them and they reduce cache efficiency.

**Reference**: [Working with AWS Elemental MediaPackage and CDNs](https://docs.aws.amazon.com/mediapackage/latest/userguide/cdns.html)

## Error code reference
<a name="documented-error-reference"></a>

Reference for documented error conditions and their causes:

**HTTP 400 Bad Request (Manifest Filtering)**  
**Documented causes**:  
+ Application of filter results in empty manifest
+ Invalid parameter names or values
+ Malformed query string syntax
+ Duplicate filter parameters
+ Parameter string exceeds 1024 characters
+ Query parameters on media playlists or segments
**Reference**: [MediaPackage manifest filtering error conditions](https://docs.aws.amazon.com/mediapackage/latest/userguide/error-conditions-and-handling.html)

**HTTP 200 OK (No Filtering Applied)**  
**Documented causes**:  
+ Filter parameter not found in available streams (returns unfiltered manifest)
+ Only subtitle streams present after filtering (returns unfiltered manifest)
**Reference**: [MediaPackage manifest filtering error conditions](https://docs.aws.amazon.com/mediapackage/latest/userguide/error-conditions-and-handling.html)

## Additional troubleshooting resources
<a name="additional-resources"></a>

For issues not covered in this topic, consult these official AWS resources:
+ [Previewing a manifest from AWS Elemental MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/userguide/endpoints-preview.html) - Use manifest preview to troubleshoot content packaging issues
+ [Increase CloudFront cache hit ratio](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cache-hit-ratio.html) - Comprehensive guide to CDN cache optimization
+ [Manifest filtering](https://docs.aws.amazon.com/mediapackage/latest/userguide/manifest-filtering.html) - Complete guide to MediaPackage filtering functionality

# 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

# Set up third-party CDNs for MediaTailor ad delivery
<a name="cdn-provider-specific"></a>

Third-party CDNs like Akamai and Fastly can significantly improve the performance and scalability of your AWS Elemental MediaTailor ad delivery while reducing bandwidth costs. However, CDN configuration for personalized advertising requires specific settings that differ from standard video delivery.

For information about passing query parameters through third-party CDNs, see [MediaTailor manifest query parameters](manifest-query-parameters.md). For advanced routing configurations using dynamic variables, see [MediaTailor dynamic ad variables for ADS requests](variables.md).

This guide walks you through the complete process of setting up your third-party CDN to work optimally with MediaTailor. You'll learn how to configure two essential behaviors:
+ **Manifest bypass:** Ensures each viewer receives personalized ad insertions by preventing manifest caching
+ **Segment caching:** Maximizes performance and reduces costs by efficiently caching video content

The configuration process typically takes 30-60 minutes and includes provider selection, setup, verification, and optimization. Once complete, you'll have a CDN configuration that delivers personalized ads efficiently while maintaining optimal viewer experience.

**Note**  
This guide focuses on Akamai and Fastly configurations. For CloudFront setup instructions, see [CloudFront integration](cloudfront-specific-recommendations.md).

## Prerequisites
<a name="cdn-3p-prerequisites"></a>

Before setting up your third-party CDN with MediaTailor, make sure you have:
+ An active MediaTailor configuration that includes your content origin and ad decision server
+ Access to your CDN's configuration interface
+ A list of file extensions used in your content (.m3u8, .mpd, .ts, and so on)
+ Your CDN provider's documentation for reference

For CloudFront setup instructions instead of third-party CDNs, see [CloudFront integration](cloudfront-specific-recommendations.md).

**Terminology**  
To understand CDN configuration requirements, you need to know these manifest types:
+ **HLS manifests**:
  + *Multivariant playlist*: The top-level manifest that contains links to media playlists
  + *Media playlist*: The second-level manifest with links to content segments
+ **DASH manifests**:
  + *MPD (Media Presentation Description)*: The standard term for DASH manifests

This guide refers to all manifest files (multivariant playlists, media playlists, and MPDs) collectively as *manifests* when discussing common configuration requirements.

For general CDN configuration principles that apply to all providers, see [Set up CDN integration with MediaTailor](cdn-configuration.md).

For CDN optimization guidance, see [Performance optimization guide for CDN and MediaTailor integrations](cdn-optimization.md).

## Configure CDN caching rules
<a name="3p-cdn-config"></a>

CDN caching configuration is critical for MediaTailor ad delivery because it determines how your content reaches viewers. Proper configuration ensures that manifests remain personalized for each viewer while segments are efficiently cached to reduce origin load and improve performance.

This configuration typically takes 15-30 minutes per CDN provider and requires two distinct behaviors:
+ **Manifest handling:** Prevents caching to ensure each viewer receives personalized ad insertions
+ **Segment caching:** Maximizes cache efficiency for video content to improve delivery performance

Follow these steps to configure your CDN's caching rules for optimal ad delivery.

Choose your CDN provider from the following tabs for specific instructions:

------
#### [ Akamai ]

Configure these two behaviors in your Akamai property:
+ Manifest handling to prevent caching
+ Segment caching for optimal performance

**Configure manifest delivery**  
Configure your Akamai CDN to avoid caching manifests so that each viewer receives personalized ads.

Manifest files contain the personalized ad insertion points that MediaTailor generates for each viewer. Caching these files would result in all viewers seeing identical ads, defeating the purpose of personalized advertising.

Follow these steps for manifest requests (files ending in .m3u8, .mpd, or .smil):

1. Create a behavior to match manifest file extensions (.m3u8, .mpd, .smil)

1. Set **Caching Option** to **No Store**

1. Configure cache keys to include all query parameters

1. Enable **Forward Host Header** for proper origin routing

1. Configure header forwarding for all headers. For minimum requirements, see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers).

**Configure segment delivery**  
Configure your Akamai CDN to cache video segments to maximize CDN efficiency and reduce origin load.

Video segments are the actual content files that can be safely cached because they don't contain personalized information. Proper segment caching reduces bandwidth costs and improves playback performance for viewers.

Follow these steps for segment requests (files ending in .ts, .mp4, .m4s, and so on): 

1. Create a behavior to match segment file extensions (.ts, .mp4, .m4s)

1. Set **Honor Origin Cache Control** to **Yes**

1. Configure default time-to-live (TTL) settings for when origin headers are missing:
   + Default TTL: 86400 seconds (24 hours)
   + Maximum TTL: 604800 seconds (7 days)

**Note**  
After configuring these behaviors, activate your property changes in Akamai Control Center.  
The changes take effect after activation.

------
#### [ Fastly ]

Create these two configurations in your Fastly service:
+ Manifest handling to prevent caching
+ Segment caching for optimal performance

**Configure manifest delivery**  
Configure your Fastly CDN to bypass caching for manifest files so that each viewer receives personalized ad content.

Manifest files must reach MediaTailor for each request to ensure proper ad personalization. Bypassing the cache for these files ensures that each viewer's unique targeting parameters are processed correctly.

Follow these steps for manifest requests:

1. Create a request condition to identify manifest paths

1. Set cache condition to **Do not cache** for these requests

1. Configure **Forward** settings to include all query parameters

1. Add `User-Agent` to your header forwarding configuration

**Configure segment delivery**  
Configure your Fastly CDN to cache video segments to improve delivery performance and reduce origin traffic.

Segment caching is essential for cost-effective delivery and optimal viewer experience. These files are identical for all viewers and benefit significantly from CDN caching.

Follow these steps for segment requests:

1. Create a request condition to identify segment paths

1. Set **Cache Settings** to **Honor origin cache headers**

1. Configure default time-to-live (TTL) to 86400 seconds (24 hours) for when origin headers are missing

**Note**  
After making these changes, activate a new version of your Fastly service.  
The configuration takes effect after activation.

------

## Verify your CDN configuration
<a name="cdn-3p-verify"></a>

Verification ensures that your CDN configuration works correctly before you direct production traffic through it. These tests confirm that ad personalization functions properly and that caching provides the expected performance benefits.

Complete verification typically takes 10-15 minutes and should be performed from multiple geographic locations if possible.

After setting up your CDN, perform these checks to verify it's working correctly:

1. Test manifest personalization:

   1. Request the same content URL with different ad parameters

   1. Verify that each request returns different ad insertions

1. Test segment caching:

   1. Check CDN metrics for segment cache hit ratio (should be greater than 90%)

   1. Monitor origin traffic to confirm it's lower than direct delivery

1. Test playback performance:

   1. Play content through your CDN from different locations

   1. Verify smooth playback with no buffering issues

For comprehensive testing methodologies and advanced validation procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md).

## Optimize CDN performance
<a name="cdn-3p-optimize"></a>

After verifying your basic configuration, implement these optimizations to maximize performance and minimize costs:

### Monitor key performance metrics
<a name="cdn-3p-optimize-monitoring"></a>

Track these metrics to ensure optimal performance:

Cache hit ratio  
**Target:** Greater than 90% for video segments  
**Impact:** Higher ratios reduce origin load and improve viewer experience  
**Monitor:** Check your CDN provider's analytics dashboard daily

Origin response time  
**Target:** Less than 200ms for manifest requests  
**Impact:** Faster manifest delivery reduces startup time for viewers  
**Monitor:** Set up alerts for response times exceeding 500ms

Error rates  
**Target:** Less than 0.1% for all requests  
**Impact:** High error rates indicate configuration issues or origin problems  
**Monitor:** Set up alerts for error rates exceeding 1%

### Fine-tune caching behavior
<a name="cdn-3p-optimize-tuning"></a>

Adjust these settings based on your content characteristics and viewer patterns:

Segment TTL optimization  
**Live content:** Use shorter TTL (1-4 hours) to ensure timely updates  
**VOD content:** Use longer TTL (24-48 hours) to maximize cache efficiency  
**Ad segments:** Consider shorter TTL (30 minutes to 2 hours) for frequently updated ad content  
For comprehensive TTL recommendations and caching strategies across all MediaTailor workflows, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

Geographic optimization  
**Multi-region origins:** Configure origin selection based on viewer location  
**Edge locations:** Enable additional edge locations in regions with high viewer concentration  
**Failover:** Configure backup origins for high availability

### Optimize costs
<a name="cdn-3p-optimize-cost"></a>

Implement these strategies to reduce CDN costs while maintaining performance:
+ **Compression:** Enable gzip compression for manifest files to reduce bandwidth usage
+ **Purging strategy:** Implement selective cache purging instead of full cache clears
+ **Traffic analysis:** Review traffic patterns monthly to identify optimization opportunities
+ **Tier selection:** Use appropriate CDN service tiers based on your performance requirements

## Troubleshoot third-party CDN issues
<a name="cdn-3p-troubleshooting"></a>

CDN configuration issues typically manifest as either ad personalization problems or performance degradation. Use this systematic approach to identify and resolve the most common issues that affect MediaTailor ad delivery.

Most troubleshooting can be completed within 15-30 minutes by checking the specific symptoms and applying the corresponding solutions.

If viewers experience problems with ad delivery or playback quality, use this guide to identify and resolve common CDN configuration issues:

Akamai: Cached manifests  
**Symptom:** Viewers see identical ads even when you configure different targeting parameters.  
**Solution:** Verify that you applied the **No Store** caching option to manifest paths.  
Also verify that you included query parameters in the cache key.

Fastly: Incorrect cache keys  
**Symptom:** Viewers experience inconsistent ad personalization.  
Viewers might also see ads intended for other viewers.  
**Solution:** Verify that you configured the **Forward** settings to include all query parameters in the cache key.

General: High origin traffic  
**Symptom:** Your origin servers experience unexpectedly high traffic  
**Solution:** Verify segment caching settings and time-to-live (TTL) values.  
Check cache hit ratios in your CDN metrics.

General: Playback errors  
**Symptom:** Viewers experience buffering or playback failures  
**Solution:** Check CDN routing rules and origin health.  
Verify that all required headers are being forwarded correctly.

**Note**  
If these solutions don't resolve your issue, check your CDN provider's documentation. You can also contact their support team for additional troubleshooting steps.

For general CDN troubleshooting guidance, see [Troubleshoot issues with MediaTailor and CDN integration](cdn-troubleshooting.md).

# Performance optimization guide for CDN and MediaTailor integrations
<a name="cdn-optimization"></a>

AWS Elemental MediaTailor performance can be maximized through systematic content delivery network (CDN) optimization. Whether you're implementing server-side ad insertion (SSAI), channel assembly, or combined workflows, the optimization principles and performance targets remain consistent. This guide provides comprehensive optimization techniques and benchmarks that apply across all MediaTailor implementations.

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

**Optimization workflow overview:**

1. **Configure caching** - Set appropriate TTL values and cache behaviors

1. **Optimize routing** - Configure request routing and origin policies

1. **Measure performance** - Track against established benchmarks

1. **Apply advanced techniques** - Implement additional optimization features

**Topics**
+ [Caching optimization](cdn-optimize-caching.md)
+ [Request routing optimization](cdn-optimize-routing.md)
+ [Performance benchmarks](cdn-performance-benchmarks.md)
+ [Advanced optimization](cdn-advanced-optimization.md)

# Caching optimization for CDN and MediaTailor integrations
<a name="cdn-optimize-caching"></a>

AWS Elemental MediaTailor caching requirements vary by workflow type and content format. Proper caching configuration is critical for optimal performance, cost efficiency, and viewer experience. The following sections provide detailed caching guidance for different MediaTailor implementations.

## Server-side ad insertion (SSAI) caching
<a name="ssai-caching-optimization"></a>

For server-side ad insertion workflows, personalized manifests cannot be cached, but content and ad segments should be cached aggressively:


**SSAI CDN caching settings**  

| Content type | TTL | Path pattern | Cache key elements | 
| --- | --- | --- | --- | 
| Multivariant playlists | 0 seconds | /v1/master/\$1 | URL path \$1 all query parameters | 
| Media playlists | 0 seconds | /v1/manifest/\$1 | URL path \$1 all query parameters | 
| DASH MPDs | 0 seconds | /v1/dash/\$1 | URL path \$1 all query parameters | 
| Content segments | 24\$1 hours | Content-specific paths | URL path only | 
| Ad segments | 24\$1 hours | /v1/segment/\$1 | URL path only | 
+ Set TTL of 0 seconds for personalized manifests to ensure viewers receive up-to-date ad content
+ Configure longer TTL values for content and ad segments to maximize cache efficiency
+ Set up cache behaviors that include personalization parameters in the cache key if you support targeted advertising
+ Implement request collapsing at the CDN level to efficiently handle concurrent requests

### Recommended TTL configuration settings
<a name="ssai-ttl-configuration"></a>

For optimal SSAI performance, configure your CDN cache policies with these specific TTL settings:


**SSAI TTL configuration settings**  

| Content type | TTL setting | Recommended value | 
| --- | --- | --- | 
| Ad segments | Min TTL | 1 second | 
| Ad segments | Max TTL | 86400 seconds (24 hours) | 
| Ad segments | Default TTL | 86400 seconds (24 hours) | 
| Content segments | Min TTL | 1 second | 
| Content segments | Max TTL | 86400 seconds (24 hours) | 
| Content segments | Default TTL | 86400 seconds (24 hours) | 

These settings ensure:
+ **Min TTL of 1 second**: Allows for rapid cache invalidation when needed while preventing excessive origin requests
+ **Max TTL of 24 hours**: Balances cache efficiency with content freshness requirements
+ **Default TTL of 24 hours**: Provides optimal caching for segments that don't have explicit cache-control headers

## Server-guided ad insertion (SGAI) caching
<a name="sgai-caching-optimization"></a>

Server-guided ad insertion (SGAI) enables efficient CDN caching through cacheable media manifests that use predictable URL patterns. This section focuses on CDN-specific configuration requirements for optimal SGAI performance.

### CDN caching configuration for SGAI
<a name="sgai-caching-configuration"></a>

Configure your CDN with these SGAI-specific caching behaviors:


**SGAI CDN caching settings**  

| Content type | TTL | Path pattern | Cache key elements | 
| --- | --- | --- | --- | 
| SGAI multivariant playlists (do not cache) | 0 seconds (do not cache) | /v1/master/\$1 | URL path \$1 selected query parameters | 
| SGAI media playlists | 1-4 seconds (half segment length) | /v1/i-media/\$1 | URL path \$1 selected query parameters | 
| Asset list responses (do not cache) | 0 seconds (do not cache) | /v1/interstitials/\$1 | URL path \$1 all query parameters | 
| Ad segments | 24\$1 hours | Ad-specific paths | URL path only | 

### Cache behavior configuration
<a name="sgai-cache-behavior-setup"></a>

Set up dedicated cache behaviors for SGAI content:
+ **SGAI manifest behavior** - Create a cache behavior for `/v1/i-media/*` paths with 1-4 second TTL
+ **Asset list behavior** - Create a cache behavior for `/v1/interstitials/*` paths with 0 second TTL
+ **Query parameter handling** - Include only essential targeting parameters in cache keys to maximize cache efficiency
+ **Origin request headers** - Forward necessary headers for ad targeting while maintaining cacheability

## Channel assembly caching
<a name="channel-assembly-caching-optimization"></a>

For channel assembly workflows, manifests can be cached for short periods, while segments should be cached aggressively:


**Channel assembly CDN caching settings**  

| Content type | VOD TTL | Live TTL | Path pattern | Cache key elements | 
| --- | --- | --- | --- | --- | 
| Multivariant playlists | 5-30 minutes | 5-10 seconds | Channel-specific paths | URL path \$1 all query parameters | 
| Media playlists | 5-30 minutes | 2-5 seconds | Channel-specific paths | URL path \$1 all query parameters | 
| DASH MPDs | 5-30 minutes | 5-10 seconds | Channel-specific paths | URL path \$1 all query parameters | 
| Content segments | 24\$1 hours | 5-15 minutes | Content-specific paths | URL path only | 
| Ad segments | 24\$1 hours | 24\$1 hours | Ad-specific paths | URL path only | 
+ Set short TTL values for manifests to ensure viewers receive up-to-date programming
+ Configure longer TTL values for content segments to maximize cache efficiency
+ Set up cache behaviors that include time-shift parameters in the cache key if you support time-shifted viewing
+ Include query parameters in the cache key to properly handle time-shifted viewing requests

For detailed TTL configuration settings and best practices, see [Caching optimization for CDN and MediaTailor integrations](#cdn-optimize-caching).

## Combined SSAI and channel assembly caching
<a name="combined-workflow-caching"></a>

When implementing both channel assembly and SSAI, ensure your caching strategy is consistent for both services to avoid conflicts and optimize performance:


**Combined workflow caching settings comparison**  

| Content type | Channel assembly | SSAI | Combined recommendation | 
| --- | --- | --- | --- | 
| VOD manifests | 5-30 minutes | 0 seconds | (use a separate config) | 
| Live manifests | 2-10 seconds | 0 seconds | (use a separate config) | 
| SGAI VOD manifests | 5-30 minutes | 5-30 minutes | 5-30 minutes (cacheable manifests) | 
| SGAI Live manifests | 2-4 seconds | 2-4 seconds | 2-4 seconds (cacheable manifests) | 
| Content segments | 24\$1 hours | 24\$1 hours | 24\$1 hours (consistent) | 
| Ad segments | 24\$1 hours | 24\$1 hours | 24\$1 hours (consistent) | 

This configuration maximizes cache efficiency while ensuring viewers receive up-to-date manifests for personalized ad insertion.

# Request routing optimization for CDN and MediaTailor integrations
<a name="cdn-optimize-routing"></a>

Implement these routing optimizations for all AWS Elemental MediaTailor CDN integrations:
+ Create separate cache behaviors for manifest and segment requests
+ Configure origin request policies to control header forwarding
+ Set up proper error handling and failover mechanisms
+ Implement origin shields if available in your CDN to reduce origin load
+ Implement request collapsing at the CDN level to efficiently handle concurrent requests

# Performance benchmarks for CDN and MediaTailor integrations
<a name="cdn-performance-benchmarks"></a>

When optimizing your AWS Elemental MediaTailor CDN integration, aim for these performance benchmarks. These targets apply to all MediaTailor implementations including SSAI, channel assembly, and combined workflows:

Cache Hit Ratio Targets  
Content segments: greater than 95% cache hit ratio  
Ad segments: greater than 90% cache hit ratio  
Manifests: Not applicable for SSAI (should not be cached for personalized ad insertion); 85%\$1 for channel assembly

Latency Benchmarks  
Manifest request latency: less than 100ms (P95)  
Content segment delivery: less than 50ms (P95)  
Ad segment delivery: less than 75ms (P95)  
End-to-end startup time: less than 2 seconds

Origin Load Metrics  
Origin requests per viewer: less than 0.1 requests per minute per viewer  
Origin bandwidth per viewer: less than 5% of total viewer bandwidth

Error Rate Targets  
Manifest errors: less than 0.1%  
Segment errors: less than 0.01%  
Player-reported rebuffering: less than 1%

Scalability Benchmarks  
Support for 10 times the normal traffic during peak events without degradation  
Ability to handle greater than 1000 requests per second per channel

Use Amazon CloudWatch metrics to track these performance indicators. For detailed monitoring instructions, see [Set up monitoring tools](cdn-monitoring.md#cdn-monitor-tools-setup).

# Advanced optimization techniques for CDN and MediaTailor integrations
<a name="cdn-advanced-optimization"></a>

After implementing basic caching and routing optimizations, consider these advanced techniques to further enhance performance:

## Origin Shield implementation
<a name="origin-shield-optimization"></a>

Origin Shield adds a caching layer between CDN edge locations and your origin server, reducing origin load and improving performance:
+ Enable Origin Shield for high-traffic content and live streaming
+ Choose Origin Shield locations close to your MediaTailor regions
+ Monitor Origin Shield cache hit ratios and adjust as needed
+ Consider multiple Origin Shield locations for global deployments

## Content compression optimization
<a name="compression-optimization"></a>

Optimize content compression to reduce bandwidth and improve delivery speed:
+ Enable gzip compression for manifest files
+ Configure Accept-Encoding header forwarding for MediaTailor manifest compression
+ Use Brotli compression where supported for additional bandwidth savings
+ Avoid compressing already-compressed video segments

## Regional optimization strategies
<a name="regional-optimization"></a>

Optimize performance for global audiences through regional strategies:
+ Deploy MediaTailor configurations in multiple regions for global audiences
+ Use geo-routing to direct viewers to the nearest MediaTailor region
+ Configure regional failover for high availability
+ Monitor regional performance metrics separately

# Architecture considerations for CDN and MediaTailor integrations
<a name="cdn-architecture-considerations"></a>

Position your content delivery network (CDN) correctly in your architecture to ensure optimal performance and reliability with AWS Elemental MediaTailor. The recommended architecture places the CDN between viewers and MediaTailor, not between MediaTailor and your origin.

For detailed architecture diagrams and workflow explanations, see the following topics.
+ [Ad insertion with CDN](ssai-cdn-workflow.md) for ad insertion architecture diagrams and detailed workflow
+ [Understand CDN architecture](channel-assembly-cdn-architecture.md) for channel assembly architecture diagrams and workflow

Position your CDN correctly in your architecture:

1. Place your CDN between players and MediaTailor (not between MediaTailor and your origin).

   This architecture allows your CDN to cache ad segments and content segments. At the same time, MediaTailor can generate personalized manifests for each viewer.

1. Create separate cache behaviors for different request types:
   + Manifest requests (no caching)
   + Content segments (longer TTL)
   + Ad segments (longer TTL)

1. Configure proper error handling:
   + Set up negative caching (temporarily storing error responses) to avoid overwhelming your origin with repeated requests during service disruptions. Negative caching means the CDN will temporarily store error responses (like 404 or 500 errors) to prevent repeated requests for content that doesn't exist or is temporarily unavailable.
   + Configure appropriate error response codes and retry behavior

1. Implement intermediate caching (origin shield):

   Origin shield is a feature that creates an additional caching layer between CDN edge locations and your origin server. This reduces the number of redundant requests that reach your origin server.
   + Configure an intermediate caching layer between edge locations and your origin
   + Reduce the number of redundant requests to your origin during cache misses
   + Improve cache hit ratios across your CDN infrastructure

# Advanced CDN features for MediaTailor
<a name="advanced-cdn-features"></a>

After implementing basic content delivery network (CDN) configuration, explore these advanced features to further enhance your AWS Elemental MediaTailor streaming platform's performance and reliability.

Media Quality-Aware Routing (MQAR)  
MQAR is an Amazon CloudFront feature that automatically selects the highest quality content source based on real-time network performance metrics. Instead of using a fixed origin server, MQAR dynamically routes requests to the best-performing origin based on factors like latency and throughput. This helps ensure viewers receive the highest possible quality stream even during network fluctuations.  
If you use Amazon CloudFront, implement MQAR to automatically select the highest quality content source based on real-time metrics. For details, see [CloudFront integration](cloudfront-specific-recommendations.md) in the CloudFront integration section.

Manifest filtering  
Manifest filtering allows you to customize which renditions (different quality versions of the same content) are included in the manifests that MediaTailor delivers to viewers. Filtering helps optimize bandwidth usage by removing renditions that aren't appropriate for certain devices or network conditions. For example, you might remove 4K renditions for mobile devices or low-bandwidth connections.  
For detailed information about implementing manifest filtering with AWS Elemental MediaPackage, see [MediaPackage CDN integration](mediapackage-integration.md).

Multi-CDN strategy  
A multi-CDN strategy uses multiple CDN providers simultaneously to improve reliability and performance. If one CDN experiences issues, traffic can automatically shift to another provider. This approach is particularly valuable for high-profile live events where reliability is critical.  
For information about implementing a multi-CDN strategy with MediaTailor, see [Plan CDN integration](planning-cdn-integration.md).

# Monitor MediaTailor CDN operations and performance
<a name="cdn-monitoring"></a>

Effective monitoring of your AWS Elemental MediaTailor and content delivery network (CDN) integration ensures reliable content delivery, optimal performance, and quick issue detection. This monitoring approach applies to all MediaTailor implementations including server-side ad insertion (SSAI), channel assembly, and combined workflows.

Monitoring your CDN integration enables you to:
+ Detect and resolve issues before they impact viewers
+ Track key performance indicators and maintain service quality
+ Maintain optimal cache performance and reduce origin load
+ Ensure ad insertion success rates meet business requirements

For troubleshooting parameter-related issues that may appear in monitoring data, see [MediaTailor parameter troubleshooting guide](parameter-troubleshooting.md). For information about monitoring query parameter usage, see [MediaTailor manifest query parameters](manifest-query-parameters.md).

## Essential CDN performance metrics
<a name="cdn-monitor-essential-metrics"></a>

Track these core metrics to evaluate your CDN's effectiveness with MediaTailor implementations:

Cache hit ratio  
**What it measures**: The percentage of requests served from the CDN cache versus from origin.  
**Target values**:  
+ Content segments: 95% or higher cache hit ratio
+ Ad segments: 90% or higher cache hit ratio
+ Manifests: Varies by implementation (personalized manifests should not be cached)
**Why it matters**: Higher cache hit ratios reduce origin load, improve response times, and lower bandwidth costs.

Origin request volume  
**What it measures**: The number of requests reaching your MediaTailor origin servers.  
**Target pattern**: Should remain low and stable, with occasional spikes for cache misses or new content.  
**Why it matters**: High origin request volumes indicate caching inefficiencies and can impact MediaTailor performance.

Response latency  
**What it measures**: How quickly the CDN responds to viewer requests.  
**Target values**:  
+ Cached content: Less than 100ms (P95)
+ Origin requests: Less than 500ms (P95)
+ Manifest requests: Less than 100ms (P95)
+ Segment requests: Less than 50ms (P95)
**Why it matters**: Low latency ensures smooth playback and good viewer experience.

Error rates  
**What it measures**: The percentage of requests that result in HTTP errors.  
**Target values**:  
+ 4xx errors: Less than 0.1% of total requests
+ 5xx errors: Less than 0.01% of total requests
+ Origin errors: Less than 0.05% of origin requests
**Why it matters**: High error rates indicate configuration issues or service problems that impact viewer experience.

### MediaTailor specific metrics
<a name="emt-specific-metrics"></a>

Monitor these MediaTailor metrics alongside CDN metrics for complete visibility:

Ad fill rates  
**Key metrics**: `Avail.FillRate` and `AdDecisionServer.FillRate`  
**Target values**: Above 90% for both metrics  
**Why it matters**: Directly impacts ad revenue and viewer experience

Manifest generation performance  
**Key metrics**: `GetManifest.Latency` and `GetManifest.Errors`  
**Target values**: Latency under 200ms, error rate under 1%  
**Why it matters**: Affects playback startup time and reliability

Ad decision server health  
**Key metrics**: `AdDecisionServer.Latency`, `AdDecisionServer.Errors`, and `AdDecisionServer.Timeouts`  
**Target values**: Latency under 1000ms, error rate under 5%, minimal timeouts  
**Why it matters**: ADS performance directly affects ad insertion success

## Set up monitoring tools
<a name="cdn-monitor-tools-setup"></a>

Configure these tools to monitor your MediaTailor and CDN integration effectively:

### Amazon CloudWatch integration
<a name="cloudwatch-integration"></a>

Amazon CloudWatch provides the foundation for monitoring your MediaTailor and CDN integration:

MediaTailor metrics  
MediaTailor automatically publishes metrics to CloudWatch that track requests, responses, and errors. Key metrics include:  
+ `RequestCount`: Total number of requests to MediaTailor
+ `ResponseTime`: MediaTailor response latency
+ `4xxErrorCount` and `5xxErrorCount`: Error tracking
For a complete list of MediaTailor metrics, see [Monitoring AWS Elemental MediaTailor with Amazon CloudWatch metrics](monitoring-cloudwatch-metrics.md).

CDN metrics  
Enable CDN metrics collection in CloudWatch including:  
+ Cache hit ratios for different content types
+ Origin request counts and response times
+ Error rates by status code
For CloudFront specific metrics, enable detailed monitoring in your distribution settings.

### Dashboard configuration
<a name="dashboard-configuration"></a>

Create dashboards that provide visibility into your MediaTailor and CDN performance:

1. **Create a unified dashboard**: Combine MediaTailor and CDN metrics in a single CloudWatch dashboard for complete visibility.

1. **Organize by workflow**: Group metrics by implementation type (SSAI, channel assembly, or combined workflows).

1. **Include key performance indicators**:
   + Cache hit ratio trends over time
   + Response latency percentiles (P50, P95, P99)
   + Error rate trends and spikes

For detailed dashboard creation guidance, see [CloudWatch dashboards](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html).

### Alert configuration
<a name="alert-configuration"></a>

Configure alerts to detect issues before they impact viewers:

Critical alerts  
Configure immediate alerts for severe issues:  
+ **High error rates**: Alert when 5xx errors exceed 0.1% of requests over 5 minutes
+ **Origin server issues**: Alert when origin response time exceeds 2 seconds
+ **Cache hit ratio drops**: Alert when cache hit ratio falls below 70% for manifests or 85% for segments

Warning alerts  
Configure early warning alerts for performance degradation:  
+ **Latency increases**: Alert when P95 response time exceeds 200ms
+ **Cache efficiency decline**: Alert when cache hit ratio drops below 90% for segments

## Implementation checklist
<a name="cdn-monitor-implementation-checklist"></a>

Use this checklist to ensure comprehensive monitoring coverage:

1. **Metrics collection**:
   + ✓ MediaTailor metrics enabled in CloudWatch
   + ✓ CDN detailed monitoring enabled

1. **Dashboard setup**:
   + ✓ Unified CloudWatch dashboard created
   + ✓ Key metrics visualized with appropriate time ranges
   + ✓ Dashboard shared with relevant teams

1. **Alert configuration**:
   + ✓ Critical alerts configured with immediate notification
   + ✓ Warning alerts set up for early detection
   + ✓ Alert escalation procedures documented

1. **Operational procedures**:
   + ✓ Incident response procedures documented
   + ✓ Regular review schedule established
   + ✓ Team training completed

## Related topics
<a name="cdn-monitor-related-topics"></a>

For additional guidance on specific monitoring scenarios:
+ **Performance optimization**: For detailed optimization techniques based on monitoring data, see [CDN performance optimization](cdn-optimization.md).
+ **Troubleshooting**: For detailed troubleshooting procedures using monitoring data, see your workflow-specific troubleshooting documentation.
+ **Log analysis**: For comprehensive log analysis and monitoring, see [CDN integration log analysis and error code reference for MediaTailor](cdn-log-error-reference.md).

# Testing and validation for CDN and MediaTailor integrations
<a name="cdn-integration-testing"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration requires thorough testing to ensure reliable ad delivery and optimal performance. Systematic testing helps identify integration issues before they impact viewers. Use this comprehensive approach to validate your content delivery network and MediaTailor integration across different scenarios, configurations, and load conditions.

**Related topics:**
+ For operational setup including monitoring and logging, see [CDN monitoring](cdn-monitoring.md)
+ For troubleshooting when issues occur, see [Troubleshoot CDN integration](cdn-troubleshooting.md)
+ For performance optimization guidance, see [Performance optimization guide for CDN and MediaTailor integrations](cdn-optimization.md)

**Topics**
+ [Testing prerequisites](testing-prerequisites.md)
+ [Systematic testing methodology](systematic-testing-approach.md)
+ [Pre-deployment checklist](testing-checklist.md)
+ [Testing tools reference](testing-tools-reference.md)

# Testing prerequisites and setup for CDN and MediaTailor integrations
<a name="testing-prerequisites"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration testing requires proper preparation and resource allocation. Before beginning systematic testing, ensure you have the necessary resources and tools in place.

**Required resources:**
+ Test CDN distribution configured to mirror production settings
+ Test MediaTailor configuration with known content and ad sources
+ Test content with predictable characteristics (duration, format, ad break markers)
+ Test ad decision server or mock ADS responses
+ Multiple test devices and player types

**Testing tools:**
+ `curl` for HTTP request testing
+ `ffprobe` for HLS manifest validation
+ `mp4box` for DASH manifest validation
+ Browser developer tools for network analysis
+ Video players for end-to-end testing

# Systematic testing methodology for CDN and MediaTailor integrations
<a name="systematic-testing-approach"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration testing should follow a systematic, phased approach to ensure comprehensive coverage. Follow this structured approach to comprehensively test your content delivery network and MediaTailor integration. Each phase builds on the previous one to isolate potential issues.

For additional guidance on systematic testing approaches, see [Testing for reliability](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/test-reliability.html) in the AWS Well-Architected Framework.

## Phase 1: Test direct MediaTailor connectivity
<a name="phase1-direct-emt-testing"></a>

Start by testing MediaTailor functionality without CDN involvement to establish a baseline.

1. Test manifest requests directly to MediaTailor endpoints:
   + Test HLS multivariant playlist requests: `curl -v "https://your-emt-endpoint.mediatailor.region.amazonaws.com/v1/master/hls/config-name/master.m3u8"`
   + Test DASH MPD requests: `curl -v "https://your-emt-endpoint.mediatailor.region.amazonaws.com/v1/dash/config-name/manifest.mpd"`
   + Verify manifest responses contain expected ad break markers
   + Check that segment URLs point to correct origins

1. Verify ad insertion works correctly:
   + Test with different ad targeting parameters
   + Verify ad segments are properly transcoded and available
   + Check ad break timing and duration
   + Test fallback behavior when ads are unavailable

1. Measure baseline performance:
   + Record manifest request response times
   + Measure ad decision server response times
   + Test session creation and management

**Success criteria:** All direct MediaTailor requests return HTTP 200 responses with properly formatted manifests containing expected ad content.

## Phase 2: Test basic CDN integration
<a name="phase2-basic-cdn-integration"></a>

Add CDN to the request path and test basic functionality.

1. Test manifest requests through CDN:
   + Configure CDN with simple routing rules
   + Test manifest requests through CDN endpoints
   + Verify CDN correctly forwards requests to MediaTailor
   + Check that manifest responses are not cached (TTL = 0)

1. Test segment routing:
   + Verify content segments route to origin server
   + Verify ad segments route to MediaTailor ad storage
   + Test segment caching behavior

1. Compare CDN vs direct performance:
   + Measure response time differences
   + Check for any content differences in responses
   + Verify error handling works correctly

**Success criteria:** CDN should successfully proxy requests to MediaTailor and origin servers with minimal performance impact.

## Phase 3: Test query parameter forwarding
<a name="phase3-parameter-forwarding"></a>

Add query parameter forwarding and test ad personalization.

1. Configure query parameter forwarding at the CDN:
   + Enable forwarding of all query parameters to MediaTailor
   + Test session initialization (session ID is automatically generated by MediaTailor upon first request)
   + Test with custom targeting parameters

1. Test ad personalization:
   + Verify different parameters produce different ad responses
   + Test parameter encoding and special characters
   + Check that parameters are correctly passed to ADS

1. Validate session management:
   + Test session creation and persistence
   + Verify session ID consistency across requests
   + Test session expiration handling

**Success criteria:** Ad content varies based on query parameters, and sessions are managed correctly.

## Phase 4: Test header forwarding
<a name="phase4-header-forwarding"></a>

Add header forwarding in the CDN and test device-specific targeting.

1. Configure header forwarding for all headers. For minimum requirements, see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers).

1. Test device targeting:
   + Test with different User-Agent strings (mobile, desktop, TV)
   + Verify device-specific ad responses
   + Test geographic targeting with different IP addresses

1. Validate CORS handling:
   + Test CORS headers for web player compatibility
   + Verify preflight OPTIONS requests work correctly
   + Test from different domains

**Success criteria:** Device and geographic targeting should work correctly, and web players should not encounter CORS errors.

## Phase 5: Comprehensive scenario testing
<a name="phase5-comprehensive-testing"></a>

Test across multiple scenarios to ensure robust operation.

1. Test with different player types:
   + HLS.js players in web browsers
   + Video.js players with HLS and DASH support
   + Native players on mobile devices
   + Smart TV and set-top box players

1. Test on different devices and platforms:
   + Mobile devices (iOS, Android)
   + Desktop browsers (Chrome, Firefox, Safari, Edge)
   + Smart TVs and streaming devices
   + Different operating system versions

1. Test different content types:
   + Live streaming content
   + Video on demand (VOD) content
   + Different video formats and bitrates
   + Content with different ad break patterns

1. Test ad targeting scenarios:
   + Different demographic targeting parameters
   + Geographic targeting across different regions
   + Time-based targeting (different times of day)
   + Custom business logic parameters

**Success criteria:** All player and device combinations should work correctly with appropriate ad targeting.

## Phase 6: Load and performance testing
<a name="phase6-load-performance-testing"></a>

Validate performance under realistic load conditions.

**Important**  
**Before load testing, contact [AWS Support](https://aws.amazon.com/premiumsupport/):** Before conducting load and performance testing, create an AWS Support ticket to notify the MediaTailor service team of your planned testing. This ensures:  
The service is prepared for your expected load levels
Appropriate capacity is available during your testing window
Your testing won't be mistaken for a production incident
You receive guidance on testing best practices and limitations
Include in your support ticket: expected concurrent users, testing duration, geographic regions, and any specific scenarios you plan to test.

1. Test concurrent user scenarios:
   + Simulate multiple concurrent viewers
   + Test CDN scaling and cache performance
   + Monitor origin server performance under load
   + Verify MediaTailor can handle concurrent sessions

1. Measure performance metrics:
   + Monitor response times under load
   + Check cache hit ratios meet expectations (>80% for popular content)
   + Measure time to first frame for different scenarios
   + Track error rates during peak load

1. Test failover scenarios:
   + Test behavior when ADS is unavailable
   + Test origin server failover
   + Verify error handling and recovery
   + Test CDN edge location failover

**Success criteria:** System should maintain acceptable performance under expected load with graceful degradation during failures. Ensure that you contact [AWS Support](https://aws.amazon.com/premiumsupport/) and they approve your load testing plan before execution.

# Pre-deployment testing checklist for CDN and MediaTailor integrations
<a name="testing-checklist"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration must pass comprehensive testing before production deployment. Use this checklist before deploying configuration changes to production.

**Basic functionality:**
+ ☐ Manifest requests return HTTP 200 responses
+ ☐ Content segments load correctly
+ ☐ Ad segments load correctly
+ ☐ Ad breaks appear at expected times
+ ☐ Playback transitions smoothly between content and ads

**Configuration validation:**
+ ☐ Query parameters are forwarded correctly
+ ☐ Required headers are forwarded correctly
+ ☐ Manifest caching is disabled (TTL = 0)
+ ☐ Segment caching is configured appropriately
+ ☐ CORS headers are configured for web players

**Cross-platform testing:**
+ ☐ Tested on mobile devices
+ ☐ Tested on desktop browsers
+ ☐ Tested with different player types
+ ☐ Tested both HLS and DASH formats

**Performance validation:**
+ ☐ AWS Support ticket created for load testing approval
+ ☐ Response times meet performance targets
+ ☐ Cache hit ratios are acceptable
+ ☐ Error rates are within acceptable limits
+ ☐ Monitoring and alerting are configured

# Testing tools and utilities reference for CDN and MediaTailor integrations
<a name="testing-tools-reference"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration testing requires various tools for comprehensive validation and debugging. Reference guide for tools commonly used in content delivery network and MediaTailor integration testing.

`curl` - HTTP request testing  
Test manifest requests: `curl -v "https://your-cdn-domain.com/v1/master/hls/config/master.m3u8"`  
Test with headers: `curl -H "User-Agent: TestAgent/1.0" "https://your-cdn-domain.com/..."`  
Test with parameters: `curl "https://your-cdn-domain.com/...?aws.sessionId=test123"`

`ffprobe` - HLS manifest validation  
Validate HLS syntax: `ffprobe -v quiet -print_format json -show_format "https://your-cdn-domain.com/master.m3u8"`  
Check segment information: `ffprobe -v quiet -show_entries packet=pts_time "segment.ts"`

`mp4box` - DASH manifest validation  
Validate DASH MPD: `mp4box -info "https://your-cdn-domain.com/manifest.mpd"`  
Check segment timing: `mp4box -info segment.m4s`

Browser developer tools  
Monitor network requests in the Network tab  
Check for CORS errors in the Console tab  
Inspect request/response headers  
Analyze timing and performance metrics

**Additional resources:**
+ [Troubleshooting CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Troubleshooting.html) - Comprehensive CDN troubleshooting guide
+ [Increase CloudFront cache hit ratio](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cache-hit-ratio.html) - Performance optimization guidance
+ [Monitor AWS resources](https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/monitor-aws-resources.html) - Performance monitoring best practices

# Troubleshoot issues with MediaTailor and CDN integration
<a name="cdn-troubleshooting"></a>

This comprehensive troubleshooting guide covers common content delivery network (CDN) integration issues across all AWS Elemental MediaTailor implementations including server-side ad insertion (SSAI), channel assembly, and AWS Elemental MediaPackage integration. When your CDN and MediaTailor integration experiences problems, use this systematic diagnostic approach to quickly identify root causes and implement validated solutions.

This guide applies to all MediaTailor CDN integrations regardless of your specific workflow. For issues specific to particular services or workflows, see the related troubleshooting sections referenced at the end of this guide.

**Before you begin:** Have these items ready for efficient troubleshooting:
+ Sample playback URLs that demonstrate the issue
+ CDN access logs from the time period when issues occurred
+ MediaTailor configuration name and AWS Region
+ Player type and version (for example, HLS.js 1.4.0, Video.js 8.0)
+ Device and browser information where issues occur

**Related topics:**
+ For operational setup and troubleshooting preparation, see [Troubleshoot CDN integration](#cdn-troubleshooting)
+ For log analysis and error code reference, see [CDN integration log analysis reference](cdn-log-error-reference.md)
+ For escalation and getting additional help, see [Get CDN integration support](cdn-get-help.md)

# Diagnostic checklist for MediaTailor and CDN integrations
<a name="quick-diagnostic-checklist"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration problems can manifest in various ways. Use this checklist to quickly identify the type of issue you're experiencing:

1. **Is the issue affecting all viewers or specific viewers?**
   + All viewers → Likely CDN or MediaTailor configuration issue
   + Specific viewers → Likely personalization or targeting issue

1. **Are manifests loading correctly?**
   + No → CDN routing or MediaTailor connectivity issue
   + Yes, but wrong content → Caching or personalization issue

1. **Are segments loading correctly?**
   + Content segments fail → Origin connectivity issue
   + Ad segments fail → Ad delivery or transcoding issue

1. **Are ads being inserted correctly?**
   + No ads appear → Check ADS connectivity and configuration
   + Wrong ads appear → Check ad targeting parameters and personalization
   + Ads fail to play → Check ad transcoding and segment availability

1. **Is playback smooth and uninterrupted?**
   + Buffering issues → Check CDN cache performance and origin response times
   + Playback errors → Check manifest syntax and segment availability
   + Ad transition issues → Check ad break timing and segment alignment

1. **Are there specific error codes or messages?**
   + HTTP 4xx errors → Check CDN routing and configuration
   + HTTP 5xx errors → Check origin server and MediaTailor service health
   + Player-specific errors → Check manifest format and player compatibility

**Next steps based on your diagnosis:**

CDN configuration issues  
For detailed CDN routing and caching troubleshooting, see [Troubleshoot issues with MediaTailor and CDN integration](cdn-troubleshooting.md).

Manifest and playback issues  
For manifest validation and playback troubleshooting, see [CDN integration testing procedures](cdn-testing-procedures.md).

Ad insertion and targeting issues  
For ad-specific troubleshooting including ADS connectivity and ad delivery, see your workflow-specific troubleshooting documentation.

Performance and monitoring issues  
For performance analysis and monitoring setup, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md).

Log analysis and error codes  
For detailed log analysis and error code reference, see [CDN integration log analysis and error code reference for MediaTailor](cdn-log-error-reference.md).

Testing and validation  
For comprehensive testing procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md).

If you need immediate assistance or cannot resolve the issue using the linked resources, see [Get support and troubleshooting help for CDN and MediaTailor integrations](cdn-get-help.md) for escalation procedures.

# CDN integration testing procedures
<a name="cdn-testing-procedures"></a>

Proper testing is essential before deploying your MediaTailor CDN integration to production. These testing procedures help identify configuration issues, performance problems, and compatibility issues across different devices and platforms.

## Basic integration validation
<a name="basic-integration-testing"></a>

Perform these fundamental tests to verify your CDN integration is working correctly:

1. **Test manifest delivery**:
   + Request a manifest through your CDN and verify it returns a valid response
   + Verify the manifest contains expected content and ad insertion points
   + Check that manifest URLs use your CDN domain, not the origin
   + Validate manifest syntax using HLS or DASH validation tools

1. **Verify URL rewriting**:
   + Check that content segment URLs in manifests point to your CDN domain
   + Verify ad segment URLs point to your CDN domain
   + Ensure all relative URLs are properly resolved

1. **Test content playback**:
   + Play content through a video player and verify smooth playback
   + Verify both content and ads play without interruption
   + Check for proper transitions between content and ads
   + Test seeking and scrubbing functionality

1. **Validate CDN routing**:
   + Monitor CDN access logs to ensure requests are routed correctly
   + Verify cache hit/miss patterns are as expected
   + Check that origin requests only occur for cache misses

## Advanced testing procedures
<a name="advanced-integration-testing"></a>

Perform these additional tests for comprehensive validation:

1. **Cross-platform compatibility testing**:
   + Test on multiple devices (desktop, mobile, tablet, smart TV)
   + Verify compatibility across different browsers
   + Test with various video players (HLS.js, Video.js, native players)
   + Validate on different operating systems

1. **Performance testing**:
   + Measure manifest request response times (target: <100ms for cached)
   + Test segment loading performance across different bitrates
   + Verify startup time meets performance targets
   + Test under various network conditions

1. **Ad tracking validation**:
   + Verify ad tracking beacons fire correctly
   + Check ad analytics data for accuracy
   + Test impression and completion tracking
   + Validate click-through functionality

1. **Error condition testing**:
   + Test behavior when origin is temporarily unavailable
   + Verify graceful handling of malformed requests
   + Test CDN failover scenarios
   + Validate error message clarity and usefulness

## Create a test environment
<a name="test-environment-setup"></a>

Set up a test environment that mirrors your production configuration for comprehensive validation:

1. Set up separate CDN distributions for testing:
   + Create test CDN distributions with the same cache behaviors as production
   + Configure test origins that mirror your production setup
   + Use separate domain names to avoid conflicts with production traffic

1. Create test MediaTailor configurations:
   + Set up test playback configurations with the same settings as production
   + Configure test ad decision server endpoints
   + Use test ad content that matches your production ad formats

1. Implement systematic testing processes:
   + Create testing checklists for configuration changes
   + Document test procedures for your team
   + Set up automated testing where possible

## Test across multiple scenarios
<a name="multi-scenario-testing"></a>

Validate your integration across different scenarios and conditions to ensure comprehensive coverage:

1. Test with multiple player types and devices:
   + Test with different video players (web, mobile, connected TV)
   + Validate across different operating systems and browsers
   + Test on various network conditions and connection speeds

1. Create automated testing scripts:
   + Automate manifest request validation
   + Create scripts to test ad insertion scenarios
   + Implement performance testing for high-traffic scenarios

1. Validate ad targeting and personalization:
   + Test with different user profiles and targeting parameters
   + Validate ad decision server integration
   + Test fallback scenarios when ads are unavailable

## Testing tools and techniques
<a name="testing-tools-techniques"></a>

Use these tools and techniques for effective testing:

Browser developer tools  
Use Network tab to inspect HTTP requests and responses  
Monitor console for JavaScript errors and warnings  
Verify response headers and caching behavior  
Check timing information for performance analysis

Command-line testing  
Use curl to test specific URLs and inspect headers:  

```
curl -I "https://your-cdn-domain.com/path/to/manifest.m3u8"
```
Use wget for download testing and timing analysis  
Employ tools like httpie for more readable HTTP testing

Video player testing  
Test with multiple player implementations  
Use player debug modes to inspect internal behavior  
Monitor player events and error callbacks  
Validate adaptive bitrate switching behavior

CDN analytics and monitoring  
Monitor real-time CDN metrics during testing  
Review access logs for request patterns  
Use CDN-specific testing tools when available  
Set up temporary alerts for testing validation

For additional comprehensive testing methodologies and systematic validation approaches, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md).

# Troubleshoot CDN manifest 404 errors for MediaTailor
<a name="common-integration-issues"></a>

AWS Elemental MediaTailor content delivery network (CDN) manifest 404 errors are a common integration issue that prevents playback from starting. This section provides step-by-step troubleshooting for manifest delivery failures. 

Multivariant playlist, media playlist, or MPD requests return 404 errors  
**Quick fix (try first):**  

1. Verify the MediaTailor configuration name in your URL matches exactly (case-sensitive)

1. Test the manifest URL directly against MediaTailor without CDN: `curl -v "https://your-emt-endpoint.mediatailor.region.amazonaws.com/v1/master/hls/config-name/master.m3u8"`

1. If direct test works, check CDN routing rules for manifest requests
**If quick fix doesn't work:**  
**Symptoms:** Players fail to start playback, manifest requests return HTTP 404 errors in CDN logs.  
**Example error messages:**  
+ Browser console: `"Failed to load resource: the server responded with a status of 404 (Not Found)"`
+ Player error: `"MANIFEST_LOAD_ERROR"` or `"NETWORK_ERROR"`
+ CDN logs: `GET /v1/master/hls/example-config/master.m3u8 404`
**Resolution:**  
Verify that your CDN routing rules are correctly configured to forward multivariant playlist, media playlist, and MPD requests to MediaTailor.  
Check that the MediaTailor configuration exists and is correctly set up.  
Ensure your CDN behavior patterns match the expected manifest request paths (for example, `*.m3u8`, `*.mpd`).

# Diagnose CDN manifest delivery issues and errors for MediaTailor
<a name="diagnose-manifest-issues"></a>

AWS Elemental MediaTailor content delivery network (CDN) manifest delivery problems can prevent proper ad insertion and playback. If viewers receive incorrect or inconsistent ads in multivariant playlists, media playlists, or MPDs:

1. Check for cached manifests:
   + Verify TTL settings are set to 0 for all multivariant playlist, media playlist, and MPD paths
   + Confirm that your CDN isn't caching multivariant playlists, media playlists, or MPDs despite TTL settings
   + Check CDN logs for cache status - manifest requests should show `Miss` or `RefreshHit`, not `Hit`

1. Verify CDN routing configuration:
   + Confirm manifest requests are being routed to MediaTailor endpoints, not cached or served from origin
   + Check that CDN behavior patterns correctly match manifest paths (\$1.m3u8, \$1.mpd)
   + Verify query parameters are being forwarded to MediaTailor for personalization
   + Test manifest URLs directly against MediaTailor to isolate CDN vs service issues

1. Check header forwarding configuration:
   + Verify required headers are being forwarded (see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers))
   + Confirm User-Agent header is forwarded for device-specific ad targeting
   + Check that X-Forwarded-For header is forwarded for geo-targeting
   + Ensure Accept-Encoding header is forwarded for compression support

1. Validate manifest content and structure:
   + Check that manifests contain expected ad insertion markers (EXT-X-CUE-OUT/IN for HLS)
   + Verify segment URLs in manifests use your CDN domain, not origin domains
   + Confirm ad segments are properly inserted and accessible
   + Test manifest syntax using validation tools (ffprobe for HLS, mp4box for DASH)

1. Test different scenarios:
   + Test with different session IDs to verify personalization is working
   + Test from different geographic locations to verify geo-targeting
   + Test with different User-Agent strings to verify device targeting
   + Compare manifest responses with and without CDN to identify differences

**Additional troubleshooting resources:**
+ For detailed CDN caching configuration, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md)
+ For comprehensive CDN routing setup, see [Set up CDN routing behaviors for MediaTailor](cdn-routing-behaviors.md)
+ For header forwarding requirements, see [Required headers for MediaTailor CDN integration](cdn-configuration.md#cdn-required-headers)
+ For log analysis and error codes, see [CDN integration log analysis and error code reference for MediaTailor](cdn-log-error-reference.md)
+ For testing procedures and validation, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md)

**Success criteria:** When resolved, players should start playback normally and ads should appear as expected. Manifest requests should return HTTP 200 status codes in CDN logs, and manifests should contain properly personalized ad content.

# Troubleshoot CDN segment delivery and loading issues for MediaTailor
<a name="diagnose-segment-issues"></a>

AWS Elemental MediaTailor content delivery network (CDN) segment delivery problems can cause buffering and playback interruptions. If players can't load segments or experience buffering:

1. Check CDN routing rules:
   + Verify content segments are being routed to the correct origin
   + Confirm ad segments are being routed to the correct MediaTailor ad storage location
   + Check that segment file extensions match your CDN behavior patterns
   + Verify that segment URLs in manifests use the correct CDN domain
   + For detailed instructions on setting up routing and behavior path patterns, see [Set up CDN routing behaviors for MediaTailor](cdn-routing-behaviors.md)

1. Verify CORS configuration:
   + For web players, ensure your CDN is passing through or properly setting CORS headers
   + Test with browser developer tools to identify CORS-related errors
   + Verify that preflight OPTIONS requests are handled correctly

1. Test segment accessibility and performance:
   + Test individual segment URLs directly to verify they're accessible
   + Check segment response times and identify performance bottlenecks
   + Verify segment file sizes are appropriate for your bandwidth targets
   + Test segment loading from different geographic locations

1. Validate CDN caching behavior for segments:
   + Verify content segments have appropriate TTL settings (typically longer than manifests)
   + Check that ad segments are cached appropriately based on personalization requirements
   + Monitor cache hit ratios for both content and ad segments
   + Ensure cache keys don't include unnecessary parameters that reduce cache efficiency

1. Check origin server connectivity and health:
   + Verify origin servers are responding correctly to segment requests
   + Check origin server capacity and response times under load
   + Validate that origin servers have the expected segment files available
   + Test origin failover scenarios if multiple origins are configured

1. Troubleshoot ad segment specific issues:
   + Verify ad segments are properly transcoded and available in MediaTailor
   + Check that ad segment URLs are correctly generated in manifests
   + Test ad segment loading with different ad targeting parameters
   + Monitor for ad transcoding delays that might cause segment unavailability

1. Validate player compatibility and behavior:
   + Test segment loading with different player types and versions
   + Check player buffer settings and segment request patterns
   + Verify player error handling for failed segment requests
   + Test adaptive bitrate switching and segment selection logic

**Additional troubleshooting resources:**
+ For CDN routing and behavior configuration, see [Set up CDN routing behaviors for MediaTailor](cdn-routing-behaviors.md)
+ For CDN caching optimization, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md)
+ For CORS configuration guidance, see [CDN integration security best practices for MediaTailor](cdn-security-best-practices.md)
+ For performance monitoring and analysis, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md)
+ For comprehensive testing procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md)
+ For log analysis and error diagnosis, see [CDN integration log analysis and error code reference for MediaTailor](cdn-log-error-reference.md)

**Success criteria:** When resolved, players should load segments smoothly without buffering interruptions. Segment requests should return HTTP 200 status codes with appropriate response times, and both content and ad segments should be accessible and properly cached.

# Fix CDN session management and tracking issues for MediaTailor
<a name="diagnose-session-issues"></a>

AWS Elemental MediaTailor content delivery network (CDN) session management is critical for proper ad personalization and tracking. If you encounter session-related errors or inconsistent behavior across requests:

1. Check for session ID consistency:
   + Verify that your player maintains the same session ID across all requests for a single playback session
   + Check CDN logs to confirm session IDs are being forwarded correctly
   + Ensure session IDs are properly URL-encoded in query parameters
   + Use CloudWatch Logs to verify session ID consistency across requests (see validation steps below)

1. Validate session initialization:
   + Confirm that the first manifest request successfully creates a session
   + Check for proper session parameter forwarding (for example, `aws.sessionId`)
   + Verify session initialization using debug logs (see debug log setup below)

1. Enable debug logging for detailed session troubleshooting:
   + **For server-side reporting:** Add `?aws.logMode=DEBUG` to your playback request:

     ```
     GET <mediatailorURL>/v1/master/<hashed-account-id>/<origin-id>/<asset-id>?aws.logMode=DEBUG
     ```
   + **For client-side reporting:** Include `"logMode": "DEBUG"` in your session initialization request body
   + **Important:** The `DEBUG` value is case-sensitive
   + Maximum of 10 active debug sessions allowed simultaneously

1. Use CloudWatch Logs queries to validate session behavior:
   + **Verify debug session is active:**

     ```
     fields @timestamp, @message
     | filter sessionId = "your-session-id-here"
     | filter eventType = "SESSION_INITIALIZED" # client-side reporting
     or mediaTailorPath like "/v1/master" # server-side reporting HLS
     or mediaTailorPath like "/v1/dash" # server-side reporting DASH
     ```
   + **View all events for a session:**

     ```
     fields @timestamp, @message, eventType, mediaTailorPath
     | filter sessionId = "your-session-id-here"
     | sort @timestamp asc
     ```
   + **Check manifest generation for a session:**

     ```
     fields @timestamp, responseBody, @message
     | filter mediaTailorPath like "/v1/master/" and eventType = "GENERATED_MANIFEST" and sessionId = "your-session-id-here"
     ```

1. Test session parameter forwarding through CDN:
   + Test manifest requests with session parameters directly against MediaTailor (bypassing CDN)
   + Compare session behavior with and without CDN to identify forwarding issues
   + Verify CDN query parameter forwarding configuration includes session-related parameters
   + Check that CDN doesn't cache responses that should be session-specific

**Common session error messages:**
+ `ConflictException` (HTTP 409) - Multiple simultaneous playlist requests for the same session. **Solution:** Ensure your player requests playlists one at a time according to HLS specification
+ `NotFoundException` (HTTP 404) - Session is unavailable or configuration doesn't exist. **Solution:** Check your configuration validity and reinitialize the session
+ `BadRequestException` (HTTP 400) - Invalid session ID or improperly formatted request. **Solution:** Verify request formatting and session ID validity

**Additional troubleshooting resources:**
+ For complete debug logging setup and field reference, see [Generating AWS Elemental MediaTailor debug logs](debug-log-mode.md)
+ For CloudWatch Logs query examples and log analysis, see [Writing AWS Elemental MediaTailor logs directly to Amazon CloudWatch Logs](monitoring-cw-logs.md)
+ For CDN query parameter forwarding configuration, see [Set up CDN routing behaviors for MediaTailor](cdn-routing-behaviors.md)
+ For comprehensive error code reference, see [Troubleshooting playback from MediaTailor](playback-errors.md)

**Success criteria:** When resolved, sessions should initialize correctly, maintain consistent session IDs across requests, and debug logs should show proper `SESSION_INITIALIZED` events and manifest generation without errors.

# Resolve CDN ad break timing and synchronization issues for MediaTailor
<a name="diagnose-timing-issues"></a>

AWS Elemental MediaTailor content delivery network (CDN) ad break timing must be precisely synchronized with content markers. If ads appear at incorrect times or ad break timing is inconsistent:

1. Verify ad break markers in content:
   + Check that SCTE-35 markers are properly placed in your origin content
   + Verify ad break duration matches actual ad content length
   + Confirm that ad break timing aligns with content boundaries
   + Validate SCTE-35 marker format and timing accuracy in your origin manifests
   + Test ad break markers with different content types (live vs VOD)

1. Check CDN caching impact on timing:
   + Ensure manifest TTL is set to 0 to prevent timing drift
   + Verify that time-sensitive parameters are not being cached
   + Check for clock synchronization issues between the content source, MediaTailor, and the CDN
   + Monitor for timing drift in long-running live streams
   + Verify CDN edge server time synchronization with NTP

1. Validate SCTE-35 marker implementation:
   + Verify EXT-X-DATERANGE tags include proper SCTE35-OUT and DURATION specifications
   + Check for paired SCTE35-OUT and SCTE35-IN markers when using explicit cue-in timing
   + Validate START-DATE timestamps align with actual content timing
   + Test different SCTE-35 marker formats (duration-based vs paired markers)

1. Test ad break timing across different scenarios:
   + Compare ad break timing with direct MediaTailor requests vs CDN requests
   + Test timing consistency across different CDN edge locations
   + Verify ad break timing with different player types and buffering behaviors
   + Monitor timing accuracy during peak traffic periods

1. Debug timing issues using logs and monitoring:
   + Enable debug logging to track ad break processing timing
   + Monitor CloudWatch metrics for ad insertion timing patterns
   + Check CDN logs for timing-related request patterns
   + Use player debugging tools to verify ad break timing from client perspective

**Expected timing tolerances:**
+ Ad break timing should align with SCTE-35 markers in your content
+ Ad duration should match the duration specified in your ad decision server response
+ Clock synchronization between content source, MediaTailor, and CDN should be within 1 second
+ SCTE-35 marker timing should be accurate to within 100ms of actual content timing

**Additional troubleshooting resources:**
+ For SCTE-35 marker format and implementation, see [Integrating a content source for MediaTailor ad insertion](integrating-origin.md)
+ For debug logging setup and timing analysis, see [Generating AWS Elemental MediaTailor debug logs](debug-log-mode.md)
+ For CDN caching configuration and timing impact, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md)
+ For comprehensive testing procedures including timing validation, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md)
+ For monitoring ad insertion timing and performance, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md)

**Success criteria:** When resolved, ad breaks should appear at precisely the times specified by SCTE-35 markers, with consistent timing across all CDN edge locations and player types. Debug logs should show accurate ad break processing timing without drift or synchronization errors.

# Optimize CDN performance and resolve latency issues for MediaTailor
<a name="diagnose-performance-issues"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration performance directly impacts viewer experience and ad delivery quality. If you experience slow response times or performance degradation:

## Performance measurement techniques
<a name="performance-measurement-techniques"></a>

Before troubleshooting performance issues, establish baseline measurements and ongoing monitoring:

1. Measure key performance metrics:
   + **Response times:** Manifest requests should complete within 200ms, segment requests within 100ms
   + **Cache hit ratios:** Content segments >95%, ad segments >90%
   + **Origin request volume:** Should be less than 5% of total requests when cache is optimized
   + **Time to first frame:** Initial playback should start within 2-3 seconds

1. Use performance measurement tools:
   + **CDN analytics dashboards:** Monitor cache performance, response times, and error rates
   + **CloudWatch metrics:** Track MediaTailor service metrics including GetManifest.Latency
   + **Browser developer tools:** Measure client-side performance and network timing
   + **Command-line tools:** Use curl with timing options to measure specific requests

1. Implement continuous monitoring:
   + Set up automated performance alerts for response time degradation
   + Monitor performance across different geographic regions
   + Track performance during peak traffic periods
   + Compare performance metrics before and after configuration changes

**Performance measurement resources:**
+ For comprehensive performance monitoring setup, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md)
+ For performance testing procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md)
+ For CloudWatch metrics and monitoring, see [Monitoring AWS Elemental MediaTailor with Amazon CloudWatch metrics](monitoring-cloudwatch-metrics.md)

## CDN cache performance issues
<a name="cache-performance-troubleshooting"></a>

Cache performance problems are among the most common CDN integration issues. These problems affect all MediaTailor implementations and can significantly impact viewer experience and costs.

**Low cache hit ratio**  
**Symptoms**: High origin request volume, increased latency, higher bandwidth costs, poor viewer experience  
**Target values**:  
+ Content segments: 95% or higher cache hit ratio
+ Ad segments: 90% or higher cache hit ratio
+ Manifests: Varies by implementation (personalized manifests should not be cached)
**Common causes**:  
+ Incorrect TTL settings for different content types
+ Cache key configuration includes unnecessary query parameters
+ Cache-control headers from origin not properly configured
+ Frequent cache invalidations or purges
+ Geographic distribution issues (content not cached at edge locations)
**Solutions**:  

1. Review and optimize TTL settings:
   + Content segments: Set TTL to match segment duration or longer
   + Ad segments: Set TTL to 24 hours or longer for reusable ads
   + Static assets: Set TTL to 24 hours or longer

   For comprehensive TTL recommendations and caching optimization strategies, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

1. Optimize cache key configuration:
   + Remove unnecessary query parameters from cache keys
   + Ensure only content-affecting parameters are included
   + Normalize parameter order and case sensitivity

1. Verify origin cache-control headers are properly set

1. Implement origin shield (or equivalent CDN functionality) for high-traffic implementations. Origin shield functionality is available across major CDNs but might have different names (such as CloudFront Origin Shield, Fastly Shield, Cloudflare Argo Tiered Cache). If your CDN doesn't offer this functionality, it can be enabled in MediaTailor when you contact [AWS Support](https://aws.amazon.com/premiumsupport/).

1. Review cache invalidation strategies and reduce unnecessary purges
**Validation steps**:  

1. Monitor cache hit ratios using CDN analytics dashboards

1. Test specific URLs with curl to verify cache headers

1. Compare origin request volume before and after changes

**High origin request volume**  
**Symptoms**: Unexpectedly high number of requests reaching MediaTailor origin, increased origin server load, higher costs  
**Expected pattern**: Origin requests should be less than 5% of total viewer requests when cache hit ratios are optimal  
**Common causes**:  
+ Cache misses due to low TTL values
+ Cache key fragmentation (too many unique cache keys)
+ Geographic traffic spikes in regions without cached content
+ Frequent cache invalidations
**Solutions**:  

1. Analyze request patterns to identify cache miss causes

1. Optimize TTL settings based on content type and update frequency

1. Implement cache warming strategies for new content

1. Consider origin shield implementation (available across major CDNs with different names - see [Origin Shield implementation](cdn-advanced-optimization.md#origin-shield-optimization) for details)
**Alert threshold**: Set alerts when origin requests exceed 10% of total requests or increase by 50% over baseline

## Common HTTP error resolution
<a name="http-error-troubleshooting"></a>

HTTP errors in CDN integrations often indicate configuration issues or service problems. These error patterns are consistent across all MediaTailor implementations.

**404 Not Found errors**  
**Symptoms**: Manifest or segment requests return HTTP 404, players fail to load content, "MANIFEST\$1LOAD\$1ERROR" in player logs  
**Common causes**:  
+ Incorrect CDN origin configuration (wrong MediaTailor endpoint URL)
+ Missing or incorrect cache behavior path patterns
+ URL rewriting issues in CDN configuration
+ MediaTailor configuration name or playback endpoint errors
+ Timing issues with live content (requesting future segments)
**Diagnostic steps**:  

1. Test the same URL directly against MediaTailor origin (bypass CDN)

1. Verify CDN origin configuration matches MediaTailor playback endpoint

1. Check CDN cache behavior path patterns and precedence

1. Review CDN access logs for request routing details

1. Validate MediaTailor configuration name and region settings
**Solutions**:  
+ Correct CDN origin configuration to match MediaTailor playback endpoint
+ Update cache behavior path patterns to properly route requests
+ Fix URL rewriting rules if applicable
+ Verify MediaTailor configuration exists and is active

**403 Forbidden errors**  
**Symptoms**: Requests return HTTP 403, access denied messages, authentication failures  
**Common causes**:  
+ Missing or incorrect query parameters required by MediaTailor
+ CDN not forwarding required headers or parameters
+ IP address restrictions or geographic blocking
+ Authentication token issues (if using signed URLs)
**Solutions**:  
+ Verify all required query parameters are included and forwarded
+ Check CDN configuration for header and parameter forwarding
+ Review IP restrictions and geographic settings
+ Validate authentication tokens and signing processes

**400 Bad Request errors**  
**Symptoms**: Requests return HTTP 400, malformed request errors, parameter validation failures  
**Common causes**:  
+ Malformed query parameters or URL encoding issues
+ Invalid parameter values or formats
+ Missing required parameters for specific MediaTailor features
+ URL length limitations exceeded
**Solutions**:  
+ Validate query parameter formats and URL encoding
+ Check parameter values against MediaTailor API requirements
+ Ensure all required parameters are included
+ Review URL length and consider parameter optimization

**5xx Server errors**  
**Symptoms**: Requests return HTTP 500, 502, 503, or 504 errors, intermittent service failures  
**Common causes**:  
+ MediaTailor service issues or capacity limitations
+ CDN origin connectivity problems
+ Timeout issues due to slow origin responses
+ Temporary service degradation
**Solutions**:  
+ Check AWS Service Health Dashboard for MediaTailor service status
+ Verify CDN origin connectivity and timeout settings
+ Implement retry logic with exponential backoff
+ Monitor MediaTailor CloudWatch metrics for service health
+ Contact AWS Support if issues persist

1. Measure baseline performance:
   + Test manifest request response times directly to MediaTailor (target: <200ms)
   + Measure CDN response times for manifest requests (target: <100ms for cache hits)
   + Check segment loading times from both origin and CDN

1. Analyze CDN performance:
   + Check cache hit ratios for content segments (target: >80% for popular content)
   + Verify origin shield (or equivalent CDN functionality) is enabled and configured in the same AWS Region as your origin. Different CDNs use different names for this functionality
   + Monitor CDN edge location performance and geographic distribution

**Performance benchmarks:**
+ Monitor manifest generation response times and compare against your baseline performance
+ CDN cache hits are significantly faster than origin requests
+ ADS response times should not cause manifest generation delays

**Additional troubleshooting resources:**
+ For comprehensive performance optimization strategies, see [Performance optimization guide for CDN and MediaTailor integrations](cdn-optimization.md)
+ For origin shield implementation details, see [Origin Shield implementation](cdn-advanced-optimization.md#origin-shield-optimization)
+ For CDN caching optimization, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md)
+ For performance monitoring and metrics, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md)
+ For performance testing procedures, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md)

**Success criteria:** When resolved, response times should meet target benchmarks (manifests less than 200ms, segments less than 100ms), cache hit ratios should exceed 90% for most content types, and origin request volume should be less than 5% of total requests. Performance should be consistent across all geographic regions and device types.

# Fix CDN inconsistent behavior across devices and platforms for MediaTailor
<a name="resolve-inconsistent-behavior"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration should provide consistent ad delivery across all devices and platforms. If ads behave differently across devices:

1. Ensure consistent header forwarding across all CDN behaviors.
   + Verify that User-Agent, X-Forwarded-For, and custom targeting headers are forwarded consistently
   + Check that header forwarding rules apply to all relevant cache behaviors

1. Verify player compatibility with your CDN configuration.
   + Test with multiple player types (HLS.js, Video.js, native players) to identify player-specific issues
   + Check for player-specific header requirements or URL handling differences

1. Test with multiple device types to identify device-specific issues.
   + Include mobile devices, tablets, smart TVs, and desktop browsers in your testing
   + Test different operating systems and browser versions
   + Verify that device-specific ad targeting works correctly

If you've followed these troubleshooting steps and still need assistance, see [Get CDN integration support](cdn-get-help.md).

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

Set up tools and processes to simplify troubleshooting when CDN integration issues arise. Proactive preparation makes troubleshooting faster and more effective when issues occur.

### Enable comprehensive logging
<a name="enable-comprehensive-logging"></a>

Detailed logs are essential for diagnosing CDN integration issues. Configure logging to capture the information you'll need during troubleshooting.

1. Enable detailed CDN access logs:
   + Configure logging for all cache behaviors that handle MediaTailor requests
   + Include query strings and custom headers in log entries
   + Set up log analysis tools to identify patterns and anomalies
   + Enable real-time logs for immediate issue detection during live events
   + Configure log retention policies to maintain historical troubleshooting data

1. Configure MediaTailor logging:
   + Enable access logs for your MediaTailor configurations
   + Set up CloudWatch log groups for centralized log management
   + Configure log filters to identify error patterns

1. Set up origin server logging:
   + Enable detailed access logs on your content origin servers
   + Include request headers and response codes in logs
   + Monitor origin server performance metrics

### Add diagnostic request headers
<a name="add-diagnostic-headers"></a>

Custom headers help track requests through your CDN and identify routing issues.

1. Configure CDN diagnostic headers:
   + Add a unique identifier to each request (for example, `X-Request-ID`)
   + Include CDN-specific information in request headers
   + Add edge location or POP (point of presence) information to track geographic routing
   + Include cache status headers (Hit, Miss, RefreshHit) for cache behavior analysis

1. Add response headers for debugging:
   + Include server identification headers
   + Add timing information for performance analysis
   + Include cache control headers for manifest requests

### Establish baseline performance metrics
<a name="establish-baseline-metrics"></a>

Document normal performance ranges to quickly identify anomalies during troubleshooting:

1. **Record baseline metrics**:
   + Cache hit ratios for different content types
   + Response time percentiles (P50, P95, P99)
   + Error rates by status code
   + Request volume patterns by time of day

1. **Document performance expectations**:
   + Target cache hit ratios (95%\$1 for content, 90%\$1 for ads)
   + Acceptable response times (<100ms cached, <500ms origin)
   + Maximum acceptable error rates (<1% for 4xx, <0.1% for 5xx)

1. **Create performance dashboards**: Set up monitoring dashboards that show current metrics compared to baseline values.

### Prepare troubleshooting tools
<a name="prepare-troubleshooting-tools"></a>

Set up tools and access permissions needed for effective troubleshooting:

1. **Command-line tools**:
   + `curl` for testing HTTP requests and responses
   + `dig` or `nslookup` for DNS troubleshooting
   + HLS/DASH validation tools for manifest verification
   + Log analysis tools (grep, awk, or specialized log analyzers)

1. **Access permissions**:
   + CDN management console access for configuration review
   + MediaTailor console access for configuration verification
   + CloudWatch access for metrics and log analysis
   + Origin server access for backend troubleshooting

1. **Documentation**:
   + Network architecture diagrams
   + CDN and MediaTailor configuration documentation
   + Contact information for escalation procedures
   + Troubleshooting runbooks for common scenarios

## Workflow-specific troubleshooting guides
<a name="workflow-specific-troubleshooting"></a>

This universal troubleshooting guide covers common issues across all MediaTailor CDN integrations. For issues specific to particular workflows or services, consult these specialized troubleshooting resources:

Server-side ad insertion (SSAI) troubleshooting  
For SSAI-specific issues including ad insertion failures, ad transition problems, and personalization issues, see workflow-specific SSAI troubleshooting documentation.  
**Common SSAI-specific issues**:  
+ Ad insertion failures and empty ad breaks
+ Ad transition timing and synchronization problems
+ Personalization and targeting issues
+ Ad tracking and analytics discrepancies

Channel assembly troubleshooting  
For channel assembly-specific issues including manifest generation problems and time-shift functionality, see channel assembly workflow documentation.  
**Common channel assembly issues**:  
+ Manifest generation and compilation errors
+ Time-shift window and DVR functionality problems
+ Source content availability and failover issues
+ Program schedule and metadata synchronization

MediaPackage integration troubleshooting  
For MediaPackage specific issues including manifest filtering and EMP endpoint problems, see [CDN integration troubleshooting](cdn-emp-troubleshooting.md).  
**Common MediaPackage integration issues**:  
+ Manifest filtering parameter errors
+ MediaPackage endpoint connectivity issues
+ EMP-specific cache behavior problems
+ MediaPackage origin authentication issues

CloudFront specific troubleshooting  
For CloudFront specific configuration and setup issues, see CloudFront integration documentation.  
**Common CloudFront issues**:  
+ Distribution configuration and cache behavior setup
+ Origin access identity and security configuration
+ CloudFront specific error codes and responses
+ Geographic restrictions and edge location issues

**Additional resources**:
+ For performance optimization guidance, see [CDN performance optimization](cdn-optimization.md)
+ For monitoring and alerting setup, see [CDN monitoring](cdn-monitoring.md)
+ For general support and assistance, see [Get CDN integration support](cdn-get-help.md)

# CDN integration log analysis and error code reference for MediaTailor
<a name="cdn-log-error-reference"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration logs provide valuable insights into performance and errors. This guide covers both CDN logs (from your content delivery network) and MediaTailor logs and error codes that are relevant to CDN integration troubleshooting. Use this reference when you need to understand what your content delivery network logs and error codes are telling you about your MediaTailor integration. This guide helps you interpret log entries and error messages to identify the root cause of issues.

**Related topics:**
+ For step-by-step troubleshooting procedures, see [Troubleshoot CDN integration](cdn-troubleshooting.md)
+ For proactive monitoring and prevention strategies, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md)
+ For escalation and getting additional help, see [Get CDN integration support](cdn-get-help.md)
+ For comprehensive MediaTailor logging configuration and resources, see [MediaTailor logging configuration resources](#mediatailor-logging-resources)
+ For CloudFront log format reference, see [CloudFront access log format](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#LogFileFormat)
+ For HTTP status code reference, see [HTTP response status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)

# CDN log interpretation and analysis techniques for MediaTailor
<a name="cdn-log-interpretation"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration generates detailed logs that help you understand request patterns and identify issues. When analyzing content delivery network logs, focus on these key indicators:

**Note:** The following examples use Amazon CloudFront terminology. Other CDN providers may use different terms for similar concepts.

HTTP status codes  
+ `200` - Successful request
+ `404` - Resource not found (check routing rules and MediaTailor configuration)
+ `403` - Access denied (check CDN security settings and origin permissions)
+ `502/503/504` - Origin server errors (check MediaTailor service health and origin connectivity)

Cache behavior indicators  
+ `Hit` - Content served from CDN cache
+ `Miss` - Content fetched from origin
+ `RefreshHit` - Cached content validated with origin
+ `Error` - Request resulted in an error

Request patterns to monitor  
+ Manifest requests should typically result in `Miss` or `RefreshHit` due to low TTL settings
+ Content segments should show `Hit` for popular content
+ Ad segments may show `Miss` due to personalization

**Service health monitoring**

When analyzing CDN logs and troubleshooting issues, check MediaTailor service health to determine if problems are service-related:

AWS Service Health Dashboard  
Check current MediaTailor service status and any ongoing service events  
Access: [AWS Service Health Dashboard](https://status.aws.amazon.com/)  
Use this when: You see widespread 5xx errors or service timeouts in CDN logs

AWS Personal Health Dashboard  
View account-specific service health notifications and maintenance events  
Access: [AWS Personal Health Dashboard](https://console.aws.amazon.com/phd/home)  
Use this when: You need account-specific service health information or maintenance notifications

Amazon CloudWatch metrics monitoring  
Monitor MediaTailor service health indicators through CloudWatch metrics:  
+ `GetManifest.Errors` - Track manifest generation errors
+ `GetManifest.Latency` - Monitor response time performance
+ `AdDecisionServer.Errors` - Monitor ad server connectivity issues
+ `Origin.Errors` - Track origin server connectivity problems
Access: [CloudWatch Console](https://console.aws.amazon.com/cloudwatch/home)  
Use this when: You need detailed service performance metrics and historical trends

**Service health troubleshooting workflow:**

1. Check AWS Service Health Dashboard for current service status

1. Review AWS Personal Health Dashboard for account-specific notifications

1. Monitor CloudWatch metrics for service performance indicators

1. Correlate service health status with CDN log patterns and error rates

1. If service health is normal, focus on CDN configuration and origin server issues

**CDN log analysis resources**
+ [CloudFront access logs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html) - Complete guide to CDN log format and fields
+ [CloudFront real-time logs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/real-time-logs.html) - Real-time log streaming and analysis
+ [Analyzing log data with CloudWatch Logs Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html) - Advanced log querying and analysis
+ [Monitor workload resources](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/monitor-workload-resources.html) - Well-Architected monitoring patterns

**Topics**
+ [CDN log interpretation](cdn-log-interpretation.md)
+ [Error codes reference](emt-error-codes-reference.md)
+ [Log analysis tools](log-analysis-techniques.md)
+ [MediaTailor logging configuration resources](#mediatailor-logging-resources)

# MediaTailor error codes and CDN integration troubleshooting
<a name="emt-error-codes-reference"></a>

AWS Elemental MediaTailor error codes provide specific information about integration issues when passed through your content delivery network (CDN). When MediaTailor returns errors through your content delivery network, these codes indicate specific issues:

**Note:** These error codes are returned by MediaTailor and passed through your CDN. For CDN-specific errors, consult your CDN provider's documentation.

400 Bad Request  
**Common causes:** Malformed query parameters, missing required parameters, invalid session IDs  
**Check:** CDN query string forwarding configuration, parameter encoding

403 Forbidden  
**Common causes:** Client player requesting a segment that does not exist or lacks permission to access. For ad segments, MediaTailor might have specified a non-existent segment (contact [AWS Support](https://aws.amazon.com/premiumsupport/) to investigate). For content segments, origin provider access restrictions or authentication issues  
**Check:** For ad segments: contact [AWS Support](https://aws.amazon.com/premiumsupport/) if MediaTailor is generating invalid segment URLs. For content segments: Verify origin server permissions, authentication credentials, and access policies. Check if segments exist at the requested URLs

404 Not Found  
**Common causes:** MediaTailor configuration doesn't exist or is inactive, incorrect playback URL path, manifest or segment requests to non-existent resources  
**Check:** Verify MediaTailor configuration exists and is active, confirm playback URL matches the `ManifestEndpointPrefix` from `GetPlaybackConfiguration`, check CDN routing rules forward requests to correct MediaTailor endpoints

500 Internal Server Error  
**Common causes:** Origin server issues, ADS connectivity problems, manifest processing errors  
**Check:** Origin server health, ADS response validity, MediaTailor service status

502 Bad Gateway  
**Common causes:** Origin server unreachable, invalid origin response, `UnsupportedManifestException` due to HLS playlist alignment issues (SCTE markers not aligned across playlists, missing SCTE markers on some playlists, inconsistent ad break timing across bitrate variants)  
**Check:** Origin server connectivity and firewall rules, DNS resolution, HLS playlist consistency across all bitrate variants, SCTE-35 marker alignment on same segments across all playlists, verify all playlists contain required ad break markers

**Error code analysis resources:**
+ [Troubleshooting MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/troubleshooting.html) - Complete MediaTailor error code reference
+ [Troubleshooting CloudFront error responses](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/troubleshooting-response-errors.html) - CDN-specific error analysis
+ [HTTP response status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) - Comprehensive HTTP status code reference
+ [Failure management](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/failure-management.html) - Well-Architected error handling patterns

# CDN log analysis tools and monitoring techniques for MediaTailor
<a name="log-analysis-techniques"></a>

AWS Elemental MediaTailor content delivery network (CDN) integration generates large volumes of log data that require efficient analysis tools and techniques. Use these approaches to efficiently analyze content delivery network and MediaTailor logs:
+ **Command-line analysis:** Use tools like `grep`, `awk`, and `sort` to filter and analyze log patterns
+ **Amazon CloudWatch Logs Insights:** Query CDN and MediaTailor logs with SQL-like syntax for advanced analysis
+ **Third-party tools:** Consider log analysis platforms for comprehensive monitoring and alerting
+ **Custom dashboards:** Create visualizations that combine CDN metrics with MediaTailor performance data

If you need additional assistance with log analysis or interpreting complex error patterns, see [Get CDN integration support](cdn-get-help.md).

**Log analysis tools and resources:**
+ [CloudWatch Logs Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html) - SQL-like queries for log analysis
+ [Amazon OpenSearch Service](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) - Advanced log search and analytics
+ [CloudWatch dashboards](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html) - Custom visualization and monitoring
+ [Instrumenting distributed systems for operational visibility](https://aws.amazon.com/builders-library/instrumenting-distributed-systems-for-operational-visibility/) - Advanced observability patterns
+ [Design workload observability](https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/design-workload-observability.html) - Well-Architected observability guidance

## MediaTailor logging configuration resources
<a name="mediatailor-logging-resources"></a>

In addition to CDN logs, MediaTailor provides comprehensive logging capabilities for monitoring ad insertion, manifest generation, and service interactions. Use these resources to configure and analyze MediaTailor logs:

MediaTailor manifest and service logs  
Configure and analyze logs for manifest generation, origin interactions, and service events:  
+ [AWS Elemental MediaTailor manifest logs description and event types](log-types.md) - Complete reference for MediaTailor manifest logs and event types
+ [Viewing AWS Elemental MediaTailor logs](monitoring-through-logs.md) - Guide to viewing and interpreting MediaTailor logs

Vended logs configuration  
Configure flexible log delivery to multiple destinations with cost optimization:  
+ [Using vended logs to send AWS Elemental MediaTailor logs](vended-logs.md) - Configure log delivery to Amazon S3, Firehose, or CloudWatch Logs
+ [Migrating your AWS Elemental MediaTailor logging strategy](vended-logs-migrate.md) - Migration guide for existing logging configurations

CloudWatch Logs integration  
Integrate MediaTailor logs with CloudWatch for monitoring and analysis:  
+ [Viewing AWS Elemental MediaTailor logs](monitoring-through-logs.md) - CloudWatch Logs configuration and analysis
+ [CloudWatchInsights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html) - Advanced log querying and analysis

Ad-specific logging  
Monitor ad insertion performance and troubleshoot ad-related issues:  
+ ADS interaction logs - Monitor ad decision server communication and errors

**Key differences between CDN and MediaTailor logs:**
+ **CDN logs**: Show request/response patterns, cache behavior, and network-level errors from your content delivery network
+ **MediaTailor logs**: Show ad insertion details, manifest generation events, origin interactions, and service-specific errors
+ **Combined analysis**: Use both log types together for complete visibility into your streaming workflow

For comprehensive monitoring that combines both CDN and MediaTailor logging, see [Monitor MediaTailor CDN operations and performance](cdn-monitoring.md).

# Automate MediaTailor and CDN with CloudFormation
<a name="automating-cdn-integration"></a>

Automating AWS Elemental MediaTailor with a content delivery network (CDN) using AWS CloudFormation streamlines your ad insertion workflow and improves reliability.

This section shows you how to use AWS CloudFormation (AWS infrastructure as code service) to automatically set up AWS Elemental MediaTailor with a content delivery network (CDN). Although you can manually configure this integration as described in previous sections, using CloudFormation saves time and reduces errors by automating the entire process with a single template.

If you're new to CloudFormation, it's a service that lets you create a template file that defines all of the AWS resources that you need. When you deploy this template, CloudFormation automatically creates and configures those resources for you, ensuring that they work together correctly.

For more information about CloudFormation, see the [CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html). For information about MediaTailor resource types in CloudFormation, see [AWS::MediaTailor Resource Type Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_MediaTailor.html).

**Topics**
+ [Why use AWS CloudFormation](cloudformation-benefits.md)
+ [Prepare for deployment](prepare-cloudformation-deployment.md)
+ [Deploy the template](deploy-cloudformation-template.md)
+ [Use the deployed resources](use-deployed-resources.md)
+ [Test and validate your deployment](test-validate-deployment.md)
+ [Troubleshoot deployment issues](troubleshoot-deployment-issues.md)
+ [Customize the template](customize-cloudformation-template.md)
+ [Template reference](cloudformation-template-reference.md)

# Why use CloudFormation for MediaTailor and CDN integration
<a name="cloudformation-benefits"></a>

AWS Elemental MediaTailor automation with AWS CloudFormation provides significant advantages for broadcast professionals managing streaming workflows. Manually configuring MediaTailor with a content delivery network (CDN) can be time-consuming and error-prone. Using CloudFormation automation offers the following advantages.
+ **Consistency**: Ensures the same configuration is deployed every time, reducing human error.
+ **Version control**: Store your infrastructure as code in a version control system for tracking changes.
+ **Rapid deployment**: Deploy complex configurations in minutes instead of hours of manual configuration.
+ **Environment replication**: Easily replicate configurations across development, testing, and production environments.
+ **Documentation**: The template itself serves as documentation of your infrastructure.

Here's how the automated workflow compares to manual configuration:


| Manual setup (multiple steps) | Automated setup (single template) | 
| --- | --- | 
| Create MediaTailor playback configuration | Deploy one CloudFormation template with parameters | 
| Create CloudFront distribution | 
| Configure cache behaviors | 
| Set up security configurations | 

The automated workflow for setting up MediaTailor with CloudFront follows these steps:

1. Deploy the CloudFormation template with your content origin and ad server parameters

1. CloudFormation creates and configures all necessary resources:
   + MediaTailor playback configuration for ad insertion
   + CloudFront distribution with appropriate cache behaviors
   + Security configurations for content protection

1. Use the CloudFormation outputs to access your ad-enabled stream URLs

1. Stream your content with dynamically inserted ads

# Prepare for CloudFormation deployment of CDN and MediaTailor integrations
<a name="prepare-cloudformation-deployment"></a>

AWS Elemental MediaTailor deployment with AWS CloudFormation requires specific prerequisites and preparation steps. Before you begin working with CloudFormation to integrate MediaTailor and Amazon CloudFront, make sure you have the following.
+ An AWS account with permissions to create MediaTailor, CloudFront, and CloudFormation resources
+ A content origin where your video content is hosted (such as AWS Elemental MediaPackage, Amazon S3, or another origin server)
+ An ad decision server (ADS) that can respond to VAST requests

Before deploying the CloudFormation template, gather these required parameters:

`AdServerUrl`  
URL of the VAST ad server for dynamic ad insertion. A static VAST endpoint is provided for testing.

`ContentOriginDomainName`  
Domain name of your content origin without protocol (e.g., *mediapackage-domain.mediapackagev2.us-west-2.amazonaws.com*, *mybucket.s3.amazonaws.com*, or *custom-origin.example.com*). Do not include http:// or https:// prefixes or any paths.

`ContentOriginType`  
The type of content origin:  
+ *mediapackagev2*: For AWS Elemental MediaPackage origins
+ *s3*: For Amazon S3 bucket origins
+ *custom*: For any other origin type

The template will create several AWS resources that work together to deliver your content with personalized ads. The following describes what each component does:

## Origin access control
<a name="origin-access-control-resource"></a>

Origin Access Control (OAC) is a security feature that ensures your content can only be accessed through CloudFront, not directly from your origin server. This helps protect your content from unauthorized access.

For MediaPackage and Amazon S3 origins, the template creates an Origin Access Control (OAC) resource to secure access to your content. 

## MediaTailor playback configuration
<a name="mediatailor-resource"></a>

The MediaTailor playback configuration is the core component that handles ad insertion. It receives content from your origin, requests ads from your ad server, and combines them into a personalized stream for each viewer.

The template creates an MediaTailor playback configuration with the following settings:
+ Video content source pointing to your CloudFront distribution
+ Ad decision server URL configured to your specified VAST endpoint
+ Live pre-roll configuration for ad insertion during live streams
+ CDN configuration with appropriate segment URL prefixes

## CloudFront distribution
<a name="cloudfront-resource"></a>

The CloudFront distribution delivers your content to viewers worldwide with low latency. It handles different types of requests (manifests, content segments, ad segments) and routes them to the appropriate origins.

For broadcast professionals new to CDNs, here are some key terms:

Origin  
A server where your original content is stored (like MediaPackage or Amazon S3)

Cache behavior  
Rules that determine how different types of content are cached and delivered

Cache policy  
Settings that control how long content is cached and what request components affect caching

The template creates a CloudFront distribution with the following components:
+ Three origins:
  + Content origin (MediaPackage, Amazon S3, or custom)
  + MediaTailor manifests origin
  + MediaTailor segments origin
+ Cache behaviors with appropriate patterns:
  + Default behavior for content segments
  + Behavior for MediaTailor ad segments (/tm/\$1)
  + Behavior for MediaTailor interstitial media (/v1/i-media/\$1)
  + Behavior for personalized manifests (/v1/\$1)
  + Behavior for segment redirect requests (/segment/\$1)
+ Optimized cache policies for each behavior:
  + `CachingOptimized` for cacheable content
  + `CachingDisabled` for personalized manifests
+ Origin request policies to ensure proper header forwarding
+ Response header policies for CORS support

# Deploy the CloudFormation template for CDN and MediaTailor integrations
<a name="deploy-cloudformation-template"></a>

AWS Elemental MediaTailor deployment using the AWS CloudFormation template is straightforward once you understand what the template will create. This process takes about 15-30 minutes, with most of the time spent waiting for the CloudFront distribution to deploy.

To deploy the CloudFormation template and set up your automated ad insertion workflow:

**To deploy the MediaTailor CloudFormation template**

1. Download the CloudFormation template from the AWS Elemental MediaTailor GitHub repository or copy it from the [AWS CloudFormation template reference for AWS Elemental MediaTailor and Amazon CloudFront integration](cloudformation-template-reference.md).

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

1. Choose **Create stack** > **With new resources (standard)**.

1. Under **Specify template**, choose **Upload a template file** and upload the template.

1. Enter a stack name and provide values for the required parameters:
   + **AdServerUrl**: URL of your VAST ad server (e.g., https://*your-ad-server.com*/vast)
   + **ContentOriginDomainName**: Domain name of your content origin without protocol (e.g., *mediapackage-domain.mediapackagev2.us-west-2.amazonaws.com*)
   + **ContentOriginType**: Select the type of content origin:
     + *mediapackagev2*: For AWS Elemental MediaPackage origins
     + *s3*: For Amazon S3 bucket origins
     + *custom*: For any other origin type

1. Review the configuration and choose **Create stack**.

1. Wait for the stack creation to complete, which typically takes 5-10 minutes. You can monitor progress in the **Events** tab.

1. Once complete, navigate to the **Outputs** tab to find the URLs for your HLS and DASH manifests.

**Note**  
If you're using AWS Elemental MediaPackage as your content origin, make sure your MediaPackage endpoints are properly configured and accessible. For more information, see [MediaPackage CDN integration](mediapackage-integration.md).

# Use the CloudFormation deployed resources for CDN and MediaTailor integration
<a name="use-deployed-resources"></a>

AWS Elemental MediaTailor resources deployed by the AWS CloudFormation stack provide several important outputs that you'll use to access your content with ad insertion. After the CloudFormation stack is created successfully, you'll need to understand how to use the outputs to access your content with ads inserted. This is similar to how you would use MediaTailor URLs in a manual setup, but the CloudFormation deployment provides these URLs automatically.

After successful deployment, the CloudFormation stack provides several important outputs that you'll use to access your content with ad insertion:

`CloudFrontDomainName`  
The domain name of your CloudFront distribution (e.g., *d1234abcdef.CloudFront.net*)

`HlsManifestUrl`  
Base URL for HLS manifests with ad insertion (e.g., https://*d1234abcdef.CloudFront.net*/v1/master/*12345*/*my-playback-config*/)

`DashManifestUrl`  
Base URL for DASH manifests with ad insertion (e.g., https://*d1234abcdef.CloudFront.net*/v1/dash/*12345*/*my-playback-config*/)

`MediaTailorPlaybackConfigName`  
Name of the created MediaTailor playback configuration (such as *my-stack-PlaybackConfig*)

## Construct playback URLs
<a name="construct-playback-urls"></a>

To create the complete playback URL for your content with ads, you'll need to combine the base URL from the CloudFormation outputs with your specific manifest path. This is a critical step for broadcast professionals to understand, as it connects your existing content with the ad insertion system.

1. Start with the appropriate manifest URL from the outputs:

   ```
   HlsManifestUrl: https://d1234abcdef.CloudFront.net/v1/master/12345/my-playback-config/
   ```

1. Append your specific manifest path:

   ```
   Your manifest path: channel/index.m3u8
   ```

1. The complete playback URL becomes:

   ```
   https://d1234abcdef.CloudFront.net/v1/master/12345/my-playback-config/channel/index.m3u8
   ```

Use this URL in your video player to play content with dynamically inserted ads.

**Tip**  
If you're not sure what your manifest path should be, check your origin server. For MediaPackage origins, this is the path to your endpoint's HLS or DASH manifest. For Amazon S3 origins, this is the path to your manifest file within the bucket.

For more information about MediaTailor URL structure, see [Set up CDN integration with MediaTailor](cdn-configuration.md).

## Configure a video player
<a name="configure-video-player"></a>

After you have your playback URL, you need to configure a video player to use it. For broadcast professionals, this is similar to configuring a player for any HLS or DASH stream, but now the stream will include personalized ads. Here's a simple example using the popular HLS.js player:

```
<!DOCTYPE html>
<html>
<head>
    <title>MediaTailor Playback Example</title>
    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
</head>
<body>
    <video id="video" controls style="width: 640px; height: 360px;"></video>
    
    <script>
        const video = document.getElementById('video');
        const mediaUrl = 'https://<replaceable>d1234abcdef.CloudFront.net</replaceable>/v1/master/<replaceable>12345</replaceable>/<replaceable>my-playback-config</replaceable>/<replaceable>channel/index.m3u8</replaceable>';
        
        if (Hls.isSupported()) {
            const hls = new Hls();
            hls.loadSource(mediaUrl);
            hls.attachMedia(video);
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
            video.src = mediaUrl;
        }
    </script>
</body>
</html>
```

You can also use professional broadcast players like:
+ JW Player
+ Bitmovin Player
+ THEOplayer
+ Video.js

For more information about player integration with MediaTailor, see [MediaTailor ad server integration requirements](vast.md).

# Test and validate your CloudFormation deployment for CDN and MediaTailor integration
<a name="test-validate-deployment"></a>

AWS Elemental MediaTailor deployment validation is a critical step for broadcast professionals before going live. This section guides you through testing your deployment to ensure ads are being inserted properly and content is delivered smoothly.

After deploying the CloudFormation template, follow these steps to verify that your setup is working correctly:

**To test your MediaTailor and CloudFront integration**

1. Verify that all resources were created successfully in the CloudFormation console.

1. Check that the MediaTailor playback configuration is active in the [MediaTailor console](https://console.aws.amazon.com/mediatailor/home).

1. Verify that the CloudFront distribution is deployed and enabled in the [CloudFront console](https://console.aws.amazon.com/CloudFront/home).

1. Test playback using a sample manifest:

   1. Construct the full playback URL as described in [Construct playback URLs](use-deployed-resources.md#construct-playback-urls).

   1. Use a video player that supports HLS or DASH (like VLC, JW Player, or the AWS console player).

   1. Verify that content plays and ads are inserted at the expected break points.

1. Check the MediaTailor logs in CloudWatch for any ad insertion errors.

When testing ad insertion, look for these indicators of success:
+ Smooth transitions between content and ads
+ Ads appear at the expected break points (pre-roll, mid-roll, post-roll)
+ Ad quality matches the content quality
+ No buffering or playback errors during ad transitions

For more detailed testing procedures, see [Understanding AWS Elemental MediaTailor ad insertion behavior](ad-behavior.md). For comprehensive CDN integration testing and validation, see [Testing and validation for CDN and MediaTailor integrations](cdn-integration-testing.md).

# Troubleshoot common CloudFormation deployment issues for CDN and MediaTailor integrations
<a name="troubleshoot-deployment-issues"></a>

AWS Elemental MediaTailor deployment issues can occur even with automation during deployment or playback. As a broadcast professional, understanding how to troubleshoot these issues will help you maintain a reliable streaming service with ad insertion.

If you encounter issues with your CloudFormation deployment or the resulting MediaTailor and CloudFront integration, refer to these common problems and solutions:

## CloudFormation deployment issues
<a name="deployment-troubleshooting"></a>

Stack creation fails with "Resource creation failed" error  
**Possible causes:**  
+ Invalid content origin domain name format
+ Insufficient permissions to create resources
**Solution:** Check the specific resource error in the CloudFormation events tab. Verify that the content origin domain name is correctly formatted without protocol prefixes or paths. Ensure your IAM role has sufficient permissions to create all required resources.

CloudFront distribution takes a long time to deploy  
**Cause:** CloudFront distributions typically take 15-30 minutes to fully deploy.  
**Solution:** This is normal behavior. Wait for the distribution to reach the "Deployed" state before testing.

## Playback and ad insertion issues
<a name="playback-troubleshooting"></a>

Content plays but no ads are inserted  
**Possible causes:**  
+ Ad decision server not responding or returning empty VAST
+ Content does not contain ad markers
**Solution:** Verify that your ad server is accessible and returning valid VAST responses. Check that your content has proper ad markers (SCTE-35 markers for live content or ad break tags for VOD).

403 Forbidden errors when accessing content  
**Possible causes:**  
+ Origin access control not configured correctly
+ Origin bucket or endpoint permissions issues
**Solution:** For Amazon S3 origins, verify that the bucket policy allows access from the CloudFront distribution. For MediaPackage origins, check that the origin access control is properly configured and that the endpoint is accessible.

Playback errors or buffering  
**Possible causes:**  
+ Cache behavior path patterns not matching content paths
+ Incorrect origin domain configuration
**Solution:** Verify that your cache behaviors have the correct path patterns to route requests to the appropriate origins. Check CloudFront logs to see which origin is handling the requests and confirm it's the expected one.

For broadcast professionals, these additional troubleshooting tips may help:
+ Use the Amazon CloudWatch Logs Insights to search for specific error patterns in MediaTailor logs
+ Test with a simple VAST ad server first (like the default one provided in the template) before using your production ad server
+ Verify your content's ad markers using the MediaTailor manifest inspector tool in the console
+ Check network traffic in your browser's developer tools to see if requests to the ad server are being made correctly

For additional troubleshooting, check the CloudWatch logs for both MediaTailor and CloudFront to identify specific errors. 

# Customize the CloudFormation template for CDN and MediaTailor integrations
<a name="customize-cloudformation-template"></a>

AWS Elemental MediaTailor template customization allows broadcast professionals to adapt the AWS CloudFormation template to fit specific workflow requirements. Although the basic template works for many scenarios, these customizations can help you address more complex needs.

The examples below show YAML code snippets that you can add to the template. If you're not familiar with YAML or CloudFormation syntax, consider working with a developer or AWS solutions architect to make these changes.

You can customize the CloudFormation template to meet your specific workflow requirements.

## Add or modify origins
<a name="add-modify-origins"></a>

For broadcast workflows that use multiple content sources (like primary and backup sources, or different content libraries), you can add additional origins to your CloudFront distribution:

```
Origins:
  # Add a new origin for additional content
  - Id: SecondaryContentOrigin
    DomainName: secondary-content.example.com
    CustomOriginConfig:
      OriginProtocolPolicy: 'https-only'
      OriginSSLProtocols: 
        - TLSv1.2
```

Then add a corresponding cache behavior to route specific patterns to this origin:

```
CacheBehaviors:
  - PathPattern: '/secondary-content/*'
    TargetOriginId: SecondaryContentOrigin
    ViewerProtocolPolicy: 'https-only'
    CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6  # Managed-CachingOptimized
```

## Create custom cache policies
<a name="create-custom-cache-policies"></a>

For broadcast workflows with specific caching requirements (like quality selection parameters or viewer authentication), you can create custom cache policies instead of using the managed ones. For detailed guidance on TTL values and caching strategies, see [Caching optimization for CDN and MediaTailor integrations](cdn-optimize-caching.md).

```
# Define a custom cache policy
CustomCachePolicy:
  Type: AWS::CloudFront::CachePolicy
  Properties:
    CachePolicyConfig:
      Name: !Sub '${AWS::StackName}-CustomCachePolicy'
      DefaultTTL: 86400  # 24 hours
      MaxTTL: 31536000   # 1 year
      MinTTL: 1          # 1 second
      ParametersInCacheKeyAndForwardedToOrigin:
        CookiesConfig:
          CookieBehavior: none
        HeadersConfig:
          HeaderBehavior: none
        QueryStringsConfig:
          QueryStringBehavior: whitelist
          QueryStrings:
            - quality
            - format

# Reference the custom policy in a cache behavior
CacheBehaviors:
  - PathPattern: '/custom-path/*'
    TargetOriginId: ContentOrigin
    ViewerProtocolPolicy: 'https-only'
    CachePolicyId: !Ref CustomCachePolicy
```

## Enhance MediaTailor configuration
<a name="enhance-mediatailor-config"></a>

For broadcast workflows that need advanced ad insertion features, you can enhance the MediaTailor configuration with options like ad prefetching (to reduce latency), personalization thresholds, and bumper ads.

```
MediaTailorPlaybackConfig:
  Type: AWS::MediaTailor::PlaybackConfiguration
  Properties:
    # Add ad prefetching for improved performance
    AvailSuppression:
      Mode: BEHIND_LIVE_EDGE
      Value: 00:00:00
    # Add personalization parameters
    PersonalizationThresholdSeconds: 2
    # Add bumper ads
    Bumper:
      StartUrl: https://example.com/bumper-start.mp4
      EndUrl: https://example.com/bumper-end.mp4
    # Other existing properties...
```

For more information about MediaTailor configuration options, see [Using AWS Elemental MediaTailor to insert ads](configurations.md).

## Add security features
<a name="add-security-features"></a>

For broadcast workflows with specific security requirements (like geo-restrictions or protection against DDoS attacks), you can add AWS WAF integration and geo-restrictions:

```
# Create a AWS WAF Web ACL
WebACL:
  Type: AWS::WAFv2::WebACL
  Properties:
    Name: !Sub '${AWS::StackName}-WebACL'
    Scope: CloudFront
    DefaultAction:
      Allow: {}
    VisibilityConfig:
      SampledRequestsEnabled: true
      CloudWatchMetricsEnabled: true
      MetricName: !Sub '${AWS::StackName}-WebACL'
    Rules:
      - Name: RateLimitRule
        Priority: 0
        Action:
          Block: {}
        VisibilityConfig:
          SampledRequestsEnabled: true
          CloudWatchMetricsEnabled: true
          MetricName: RateLimitRule
        Statement:
          RateBasedStatement:
            Limit: 1000
            AggregateKeyType: IP

# Reference the AWS WAF Web ACL in the CloudFront distribution
CloudFrontDistribution:
  Type: AWS::CloudFront::Distribution
  Properties:
    DistributionConfig:
      WebACLId: !GetAtt WebACL.Arn
      # Add geo-restriction
      Restrictions:
        GeoRestriction:
          RestrictionType: whitelist
          Locations:
            - US
            - CA
            - GB
      # Other existing properties...
```

For more information about CloudFormation templates, see the [AWS CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html).

For broadcast-specific CloudFormation templates and examples, see the [AWS Media Services Tools GitHub repository](https://github.com/aws-samples/aws-media-services-tools).

# AWS CloudFormation template reference for AWS Elemental MediaTailor and Amazon CloudFront integration
<a name="cloudformation-template-reference"></a>

AWS Elemental MediaTailor integration with Amazon CloudFront can be automated using the following complete AWS CloudFormation template:

```
AWSTemplateFormatVersion: '2010-09-09'
Description: |
  CloudFormation template that sets up AWS Elemental MediaTailor integration with CloudFront Distribution
  for server-side ad insertion. This template supports various content origins including MediaPackage, Amazon S3,
  and custom origins, making it versatile for different streaming architectures.

Parameters:
  AdServerUrl:
    Type: String
    Default: 'https://d1kbmkziz9rksx.CloudFront.net/VASTEndpoint.xml'
    Description: URL of the VAST ad server for dynamic ad insertion. Static VAST endpoint provided for testing. 

  ContentOriginDomainName:
    Type: String
    Description: |
      Domain name of your content origin without protocol (e.g., mediapackage-domain.mediapackagev2.us-west-2.amazonaws.com,
      mybucket.s3.amazonaws.com, or custom-origin.example.com).
      Do not include http:// or https:// prefixes or any paths.
    AllowedPattern: "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$"
    ConstraintDescription: Must be a valid domain name (e.g., example.com) without protocol or path components. IP addresses are not allowed.

  ContentOriginType:
    Type: String
    AllowedValues:
      - mediapackagev2
      - s3
      - custom
    Default: mediapackagev2
    Description: |
      The type of content origin:
      - mediapackagev2: AWS Elemental MediaPackage V2
      - s3: Amazon S3 bucket
      - custom: Any other custom origin

Resources:
  #---------------------------------------------------------------------------
  # Origin Access Control (for securing MediaPackage V2 and Amazon S3 origins)
  #---------------------------------------------------------------------------
  CloudFrontOriginAccessControl:
    Type: AWS::CloudFront::OriginAccessControl
    Condition: IsNotCustomOrigin
    Properties:
      OriginAccessControlConfig:
        Name: !Sub '${AWS::StackName}-OAC'
        OriginAccessControlOriginType: !Ref ContentOriginType
        SigningBehavior: always
        SigningProtocol: sigv4
        Description: Origin Access Control for content origin

  #---------------------------------------------------------------------------
  # MediaTailor Playback Configuration
  #---------------------------------------------------------------------------
  MediaTailorPlaybackConfig:
    Type: AWS::MediaTailor::PlaybackConfiguration
    Properties:
      Name: !Sub '${AWS::StackName}-PlaybackConfig'
      # The video content source should point to your CloudFront distribution
      VideoContentSourceUrl: !Sub 'https://${CloudFrontDistribution.DomainName}/'
      # The Ad Decision Server URL is where MediaTailor will request ads
      AdDecisionServerUrl: !Ref AdServerUrl
      # Configuration for pre-roll ads during live streams
      LivePreRollConfiguration:
        AdDecisionServerUrl: !Ref AdServerUrl
        MaxDurationSeconds: 30
      # CDN configuration for integrating with CloudFront
      CdnConfiguration:
        AdSegmentUrlPrefix: '/'
        ContentSegmentUrlPrefix: '/'
      # Set a reasonable manifest segment timeout
      ManifestProcessingRules:
        AdMarkerPassthrough:
          Enabled: false

  #---------------------------------------------------------------------------
  # CloudFront Distribution
  #---------------------------------------------------------------------------
  CloudFrontDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Enabled: true
        HttpVersion: http2and3
        IPV6Enabled: true
        Comment: !Sub 'Distribution for MediaTailor ad insertion with ${ContentOriginType} origin'
        
        # Default cache behavior points to the content origin
        DefaultCacheBehavior:
          TargetOriginId: ContentOrigin
          ViewerProtocolPolicy: 'https-only'
          # Using managed policies for optimal performance and simplicity
          CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6  # Managed-CachingOptimized
          OriginRequestPolicyId: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf # Managed-HostHeaderOnly
          ResponseHeadersPolicyId: eaab4381-ed33-4a86-88ca-d9558dc6cd63  # Managed-CORS-with-preflight-and-SecurityHeadersPolicy
          Compress: true
        
        # Define all the origins needed for the workflow
        Origins:
          # Main content origin (MediaPackage, Amazon S3, or Custom)
          - Id: ContentOrigin
            DomainName: !Ref ContentOriginDomainName
            # Apply Origin Access Control for secure origins
            OriginAccessControlId: !If [IsNotCustomOrigin, !GetAtt CloudFrontOriginAccessControl.Id, !Ref "AWS::NoValue"]
            # For custom origins, we need a CustomOriginConfig
            CustomOriginConfig:
              OriginProtocolPolicy: 'https-only'
              OriginSSLProtocols: 
                - TLSv1.2
              OriginKeepaliveTimeout: 5
              OriginReadTimeout: 30
              HTTPPort: 80
              HTTPSPort: 443
              
          # MediaTailor Manifests Origin - handles manifest manipulation for ad insertion
          - Id: MediaTailorManifests
            DomainName: !Sub 'manifests.mediatailor.${AWS::Region}.amazonaws.com'
            CustomOriginConfig:
              OriginProtocolPolicy: 'https-only'
              OriginSSLProtocols: 
                - TLSv1.2
              OriginKeepaliveTimeout: 5
              OriginReadTimeout: 30
            # Origin Shield improves caching efficiency 
            OriginShield:
              Enabled: true
              OriginShieldRegion: !Ref AWS::Region
              
          # MediaTailor Segments Origin - handles personalized ads
          - Id: MediaTailorSegments
            DomainName: !Sub 'segments.mediatailor.${AWS::Region}.amazonaws.com'
            CustomOriginConfig:
              OriginProtocolPolicy: 'https-only'
              OriginSSLProtocols: 
                - TLSv1.2
              OriginKeepaliveTimeout: 5
              OriginReadTimeout: 30
        
        # Cache behaviors to route specific request patterns to the right origin
        CacheBehaviors:
          # Handle MediaTailor segment requests for ad content which are cache-able
          - PathPattern: '/tm/*'
            TargetOriginId: MediaTailorSegments
            ViewerProtocolPolicy: 'https-only'
            CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6  # Managed-CachingOptimized
            OriginRequestPolicyId: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf  # Managed-HostHeaderOnly
            ResponseHeadersPolicyId: eaab4381-ed33-4a86-88ca-d9558dc6cd63  # Managed-CORS-with-preflight-and-SecurityHeadersPolicy
            Compress: true
            
          # Handle MediaTailor interstitial (SGAI) media requests which are cache-able
          - PathPattern: '/v1/i-media/*'
            TargetOriginId: MediaTailorManifests
            ViewerProtocolPolicy: 'https-only'
            CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6  # Managed-CachingOptimized
            OriginRequestPolicyId: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf  # Managed-HostHeaderOnly
            ResponseHeadersPolicyId: eaab4381-ed33-4a86-88ca-d9558dc6cd63  # Managed-CORS-with-preflight-and-SecurityHeadersPolicy
            Compress: true
            
          # Handle MediaTailor Personalized manifests which are not cache-able
          - PathPattern: '/v1/*'
            TargetOriginId: MediaTailorManifests
            ViewerProtocolPolicy: 'https-only'
            CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # Managed-CachingDisabled
            OriginRequestPolicyId: 59781a5b-3903-41f3-afcb-af62929ccde1 # Managed-AllViewer
            ResponseHeadersPolicyId: eaab4381-ed33-4a86-88ca-d9558dc6cd63  # Managed-CORS-with-preflight-and-SecurityHeadersPolicy
            Compress: true
            
          # Handle MediaTailor segment *redirect* requests which are not cache-able (used for server side reporting)
          - PathPattern: '/segment/*'
            TargetOriginId: MediaTailorManifests
            ViewerProtocolPolicy: 'https-only'
            CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # Managed-CachingDisabled
            OriginRequestPolicyId: 59781a5b-3903-41f3-afcb-af62929ccde1 # Managed-AllViewer
            ResponseHeadersPolicyId: eaab4381-ed33-4a86-88ca-d9558dc6cd63  # Managed-CORS-with-preflight-and-SecurityHeadersPolicy
            Compress: true

Conditions:
  IsNotCustomOrigin: !Not [!Equals [!Ref ContentOriginType, 'custom']]

Outputs:
  CloudFrontDomainName:
    Description: Domain name of the CloudFront distribution
    Value: !GetAtt CloudFrontDistribution.DomainName
    
  HlsManifestUrl:
    Description: URL for HLS manifest with ads inserted (append your manifest path)
    Value: !Sub 'https://${CloudFrontDistribution.DomainName}${MediaTailorPlaybackConfig.HlsConfiguration.ManifestEndpointPrefix}'
    
  DashManifestUrl:
    Description: URL for DASH manifest with ads inserted (append your manifest path)
    Value: !Sub 'https://${CloudFrontDistribution.DomainName}${MediaTailorPlaybackConfig.DashConfiguration.ManifestEndpointPrefix}'
    
  MediaTailorPlaybackConfigName:
    Description: Name of the MediaTailor playback configuration
    Value: !Ref MediaTailorPlaybackConfig
```

# Production-ready CloudFront configuration for MediaTailor
<a name="cf-comprehensive-configuration"></a>

This CloudFront distribution configuration provides everything you need to deliver MediaTailor content with server-side ad insertion at scale. Copy this configuration and customize it with your specific origins and requirements.

**What this configuration accomplishes**  
This configuration creates a production-ready CloudFront distribution that handles all MediaTailor request types with optimal caching and performance. It includes three origins (your content, MediaTailor segments, and MediaTailor manifests) with four cache behaviors that route requests correctly and cache content appropriately.

**When to use this configuration**  
This setup is ideal for live streaming, video-on-demand, and hybrid workflows that require server-side ad insertion.

## Three-origin architecture
<a name="cf-three-origin-architecture"></a>

MediaTailor uses a three-origin architecture pattern to optimize content delivery and ad insertion performance. Each origin serves a specific purpose in the ad insertion workflow:

Your content origin  
This is your true content origin that feeds MediaTailor. For example, this could be AWS Elemental MediaPackage V2 or another content delivery service. This origin serves your original content before ad insertion. Common examples include:  
+ MediaPackage V2 packaging configurations
+ Third-party content delivery networks
+ On-premises streaming servers
+ Amazon S3 buckets with static content

MediaTailor segments origin  
This origin uses the hostname `segments.mediatailor.region.amazonaws.com` and serves the actual ad segments after MediaTailor has encoded them. These are the video segments that contain the advertisements. This origin handles:  
+ Transcoded ad segments in the same format as your content
+ Redirected requests from the `/segment/*` path pattern
+ Ad segments that have been processed for server-side ad insertion

MediaTailor manifests origin  
This origin uses the hostname `manifests.mediatailor.region.amazonaws.com` and can be used as a regional hostname for playback configurations in the specified AWS Region. MediaTailor selects the correct playback configuration based on the path in the request. This origin provides:  
+ Personalized HLS and DASH manifests with viewer-specific ad insertion
+ Server-guided ad insertion (SGAI) manifests for cacheable content
+ Ad tracking and beacon handling for server-side reporting

With the origin hostname `manifests.mediatailor.region.amazonaws.com`, you can have multiple playback configurations that work with the same CloudFront distribution if they're in the specified Region and you include the playback configuration name in the request path. For example:
+ `https://your-distribution.cloudfront.net/v1/master/playback-config-1/manifest.m3u8`
+ `https://your-distribution.cloudfront.net/v1/master/playback-config-2/manifest.m3u8`

Select origin request policies based on content type to prevent cache poisoning while ensuring proper functionality. The key distinction is between cacheable and non-cacheable content:
+ **Manifests (non-cacheable)**: Use `AllViewer` to forward all headers needed for dynamic content. Since manifests aren't cached, there's no cache poisoning risk.
+ **Segments (cacheable)**: Use `None` for optimal performance.
+ **S3 origins**: Use `CORS-S3Origin` for Amazon S3 buckets
+ **MediaPackage origins**: Use `CORS-S3Origin` for MediaPackage V2 endpoints

![\[Origins table showing ContentOrigin, MediaTailorSegments, and MediaTailorManifests with their respective details.\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/origins-cdn.png)


## Cache behavior precedence and configuration
<a name="cf-behavior-precedence"></a>

MediaTailor requires specific cache behavior configurations to handle different types of requests properly. The precedence of cache behaviors is critical because CDNs process them in order (smallest to largest) and use the behavior for the first matching path pattern. Understanding this precedence is essential for troubleshooting:
+ **Precedence 0**: Most specific patterns (like `/tm/*`) are evaluated first
+ **Higher precedence numbers**: Less specific patterns are evaluated in order
+ **Default behavior**: Catches all requests that don't match other patterns

If requests aren't behaving as expected, check that your path patterns don't overlap in unintended ways.

![\[Table showing behaviors with path patterns, origins, and policies for different URL paths.\]](http://docs.aws.amazon.com/mediatailor/latest/ug/images/bhv.png)


### Precedence 0: Ad segments path behavior
<a name="cf-transcode-manage-behavior"></a>

This behavior handles the redirected requests from the segment path behavior, serving the actual ad segments. CloudFront applies the following behaviors to all requests with a `/tm/*` path pattern. This is the highest priority behavior because ad segment delivery is critical for uninterrupted playback.
+ **Path pattern:** `/tm/*`

  Example URLs that match this pattern:
  + `https://your-distribution.cloudfront.net/tm/ad-segment-001.ts`
  + `https://your-distribution.cloudfront.net/tm/transcoded-ad.m4s`
+ **Origin:** The origin that you created with the `segments.mediatailor.region.amazonaws.com` domain. 

  This is **MediaTailorSegments** in the example in the preceding section on origins. 
+ **Cache policy:** `Managed-CachingOptimized`

  For details about what's included in the CloudFront managed cache policy, see [CachingOptimized](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html#managed-cache-caching-optimized) in the CloudFront user guide. You can also use these same settings from the managed policy in your third-party CDN.
+ **Origin request policy:** `None`
+ **Response headers policy:** `Managed-CORS-with-preflight-and-SecurityHeadersPolicy`

  For details about what's included in the response headers policy, see [CORS-with-preflight-and-SecurityHeadersPolicy](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-cors-preflight-security) in the CloudFront user guide. 

#### Adapting these settings to other CDNs
<a name="adapting-to-other-cdns"></a>

If you're using a CDN other than CloudFront, look for equivalent settings that accomplish the following.

**Path pattern matching**  
Configure a specific behavior for the `/tm/*` path pattern to handle MediaTailor ad segments

**Cache key configuration**  
Include the `Origin` header in your cache key to ensure responses are cached separately for different origins

**Header forwarding**  
Forward the `Origin` header and other CORS-related headers to the origin

**Response header management**  
Configure your CDN to ensure the `Access-Control-Allow-Origin` header is present in responses

The specific terminology and configuration options will vary by CDN provider, but the underlying principles remain the same.

### Precedence 1: Server-guided ad insertion behavior
<a name="cf-sgai-behavior"></a>

This behavior handles [MediaTailor server-guided ad insertion overview and implementation](server-guided.md) (SGAI) requests when customers configure guided mode, which provides cacheable manifests. CloudFront applies the following behaviors to all requests with a `/v1/i-media/*` path pattern. SGAI allows for better caching performance because the manifests are not viewer-specific.
+ **Path pattern:** `/v1/i-media/*` (iMedia path for SGAI)

  Example URLs that match this pattern:
  + `https://your-distribution.cloudfront.net/v1/i-media/your-config/manifest.m3u8`
  + `https://your-distribution.cloudfront.net/v1/i-media/your-config/playlist.mpd`
+ **Origin:** The origin that you created with the `manifests.mediatailor.region.amazonaws.com` domain. 

  This is **MediaTailorManifests** in the example in the preceding section on origins. 
+ **Cache policy:** `Managed-CachingOptimized`

  For details about what's included in the CloudFront managed cache policy, see [CachingOptimized](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html#managed-cache-caching-optimized) in the CloudFront user guide. You can also use these same settings from the managed policy in your third-party CDN.
+ **Origin request policy:** `None`
+ **Response headers policy:** `Managed-CORS-with-preflight-and-SecurityHeadersPolicy`

  For details about what's included in the response headers policy, see [CORS-with-preflight-and-SecurityHeadersPolicy](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-cors-preflight-security) in the CloudFront user guide. 

### Precedence 2: Personalized manifest behavior
<a name="cf-personalized-manifest-behavior"></a>

This behavior handles personalized manifest requests. CloudFront applies the following behaviors to all requests with a `/v1/*` path pattern. CloudFront applies the following behaviors and doesn't cache personalized manifests because they contain viewer-specific ad content URLs. These behaviors apply to all requests that have a `/v1/*` path pattern. This is the core MediaTailor functionality where each viewer receives a unique manifest with personalized ad insertion.
+ **Path pattern:** `/v1/*` (standard V1 MediaTailor requests)

  Example URLs that match this pattern:
  + `https://your-distribution.cloudfront.net/v1/master/your-config/manifest.m3u8`
  + `https://your-distribution.cloudfront.net/v1/dash/your-config/manifest.mpd`
+ **Origin:** The origin that you created with the `manifests.mediatailor.region.amazonaws.com` domain. 

  This is **MediaTailorManifests** in the example in the preceding section on origins. 
+ **Cache policy:** `Managed-CachingDisabled`

  For details about what's included in the cache policy, see [CachingDisabled](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html#managed-cache-policy-caching-disabled) in the CloudFront user guide. 
+ **Origin request policy:** `AllViewer`

  For personalized manifests, use the `AllViewer` policy to forward all headers needed for dynamic content. 
+ **Response headers policy:** `Managed-CORS-with-preflight-and-SecurityHeadersPolicy`

  For details about what's included in the response headers policy, see [CORS-with-preflight-and-SecurityHeadersPolicy](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-cors-preflight-security) in the CloudFront user guide. 

**Accept-Encoding header**  
We recommend that your CDN preserves the `Accept-Encoding` header from viewers. This header gives MediaTailor instruction on compressing personalized manifests. 

In CloudFront, the `AllViewerAndCloudFrontHeaders` origin request policy includes passthrough of the `Accept-Encoding` header from the viewer. If you use a different CDN, ensure that it preserves this header.

The following is how MediaTailor handles the `Accept-Encoding` header.
+ **Legacy devices:** Older smart TVs that don't support gzip won't send the Accept-Encoding header, so MediaTailor returns uncompressed manifests
+ **Modern devices:** iPhones, Chrome browsers, and other modern clients send the Accept-Encoding header, allowing MediaTailor to compress manifests before delivery

### Precedence 3: Server-side beacon path behavior
<a name="cf-segment-path-behavior"></a>

This behavior handles requests to MediaTailor that result in redirects for [Server-side tracking](ad-reporting-server-side.md). These requests are essential for tracking beacons, so every request must be processed by MediaTailor. CloudFront applies the following behaviors to all requests with a `/segment/*` path pattern. 
+ **Path pattern:** `/segment/*`

  Example URLs that match this pattern:
  + `https://your-distribution.cloudfront.net/segment/tracking-beacon-123`
  + `https://your-distribution.cloudfront.net/segment/ad-request-456.ts`
+ **Origin:** The origin that you created with the `manifests.mediatailor.region.amazonaws.com` domain. 

  This is **MediaTailorManifests** in the example in the preceding section on origins. 
+ **Cache policy:** `Managed-CachingDisabled`

  For details about what's included in the cache policy, see [CachingDisabled](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html#managed-cache-policy-caching-disabled) in the CloudFront user guide. 
+ **Origin request policy:** `AllViewer`

  For server-side beacon requests, use the `AllViewer` policy to forward all headers needed for tracking. Since these requests aren't cached, there's no cache poisoning risk.
+ **Response headers policy:** `Managed-CORS-with-preflight-and-SecurityHeadersPolicy`

  For details about what's included in the response headers policy, see [CORS-with-preflight-and-SecurityHeadersPolicy](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-cors-preflight-security) in the CloudFront user guide. 

When MediaTailor processes these requests, it returns a 302 redirect response with a path that points to the actual segment location. For example, a request to `/segment/ad123.ts` might redirect to `/tm/encoded-ad-segment.ts` on the segments origin.

### Precedence 4: Content origin path behavior
<a name="cf-default-behavior"></a>

If the request path doesn't match any of the other patterns, CloudFront applies the default behavior. This behavior sends requests directly to the content origin, with no processing from MediaTailor. This allows direct access to your content origin (such as MediaPackage V2) when needed. CloudFront applies the following behaviors to all requests that don't include any of the prior path patterns.
+ **Path pattern:** `(*)` 
+ **Origin:** The origin that you created with the domain for your content origin. 

  This is **ContentOrigin** in the example in the preceding section on origins. 
+ **Cache policy:** `Managed-CachingOptimized`

  For details about what's included in the CloudFront managed cache policy, see [CachingOptimized](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html#managed-cache-caching-optimized) in the CloudFront user guide. You can also use these same settings from the managed policy in your third-party CDN.
**Note**  
For low latency HLS implementations, consider using a custom caching policy with Low Latency HLS (LLH) directives instead of the standard `CachingOptimized` policy.
+ **Origin request policy:** `None`
+ **Response headers policy:** `Managed-CORS-with-preflight-and-SecurityHeadersPolicy`

  Although the default content origin behavior doesn't typically face the same CORS cache poisoning risks as the ad segment behavior, it's still recommended to use the `Managed-CORS-with-preflight-and-SecurityHeadersPolicy` response headers policy and include the `Origin` header in your cache key. This ensures consistent CORS handling across all content types and prevents potential playback issues in web-based players.

  For content segments, the `Managed-CachingOptimized` cache policy provides good performance while the `Managed-CORS-with-preflight-and-SecurityHeadersPolicy` response headers policy ensures proper CORS handling. This combination allows for efficient caching while maintaining compatibility with web-based players that require CORS headers.

  Applying consistent CORS handling across both ad segments and content segments creates a more reliable playback experience and simplifies troubleshooting. Without proper CORS configuration, players might experience inconsistent behavior when transitioning between content and ads.

  For details about what's included in the response headers policy, see [CORS-with-preflight-and-SecurityHeadersPolicy](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-cors-preflight-security) in the CloudFront user guide. 

# Get support and troubleshooting help for CDN and MediaTailor integrations
<a name="cdn-get-help"></a>

AWS Elemental MediaTailor CDN integration issues can be complex to diagnose and resolve. Use this guide when you need additional help with CDN and MediaTailor integration issues that you can't resolve through self-service troubleshooting.

**Before escalating, try these self-service options:**
+ Follow the troubleshooting steps in [Troubleshoot CDN integration](cdn-troubleshooting.md)
+ Analyze your logs and error codes using [CDN integration log analysis reference](cdn-log-error-reference.md)
+ Review your monitoring setup with [Set up monitoring tools](cdn-monitoring.md#cdn-monitor-tools-setup)
+ Check the [MediaTailor troubleshooting guide](https://docs.aws.amazon.com/mediatailor/latest/ug/troubleshooting.html) for service-specific issues
+ Search [AWS re:Post](https://repost.aws/) for similar issues and community solutions
+ Review [AWS Knowledge Center](https://aws.amazon.com/premiumsupport/knowledge-center/) for common integration patterns

**Topics**
+ [When to escalate to Support](#when-to-escalate)
+ [Gather information for support](#information-to-gather)
+ [Support resources](#support-resources)
+ [Support case best practices](#support-case-best-practices)

## When to escalate MediaTailor CDN issues to AWS Support
<a name="when-to-escalate"></a>

AWS Elemental MediaTailor CDN integration issues should be escalated to AWS Support when self-service troubleshooting doesn't resolve the problem. Consider escalating to AWS Support when:

**Note:** Technical support requires a paid AWS Support plan. For support plan details and response times, see [AWS Support plans](https://aws.amazon.com/premiumsupport/plans/).
+ Issues affect production traffic or revenue
+ You've followed all troubleshooting steps without resolution
+ Error patterns suggest service-level issues
+ You need assistance with complex configuration scenarios
+ Performance issues persist despite optimization efforts

## Gather MediaTailor CDN information before contacting support
<a name="information-to-gather"></a>

AWS Elemental MediaTailor CDN integration support cases require specific configuration and diagnostic information for effective troubleshooting. Before contacting AWS Support, gather this information to help expedite resolution:

**Tip:** Having this information ready before creating your support case will significantly reduce resolution time and help support engineers understand your specific configuration.
+ **MediaTailor configuration details:**
  + Configuration name and AWS Region
  + Playback configuration ARN
  + ADS URL and integration type
+ **CDN configuration details:**
  + CDN distribution ID or configuration name
  + Cache behavior configurations for manifests and segments
  + Origin configuration and routing rules
+ **Error information:**
  + Specific error messages and HTTP status codes
  + Timestamps when issues occur
  + Sample URLs that demonstrate the problem
  + CDN and MediaTailor log entries related to the issue
+ **Testing information:**
  + Steps you've already taken to troubleshoot
  + Devices and players where the issue occurs
  + Whether the issue affects all content or specific streams
  + Frequency and pattern of the issue (intermittent, consistent, time-based)

## MediaTailor CDN integration support resources and channels
<a name="support-resources"></a>

AWS Elemental MediaTailor CDN integration support is available through multiple channels to help you resolve issues and optimize your implementation:
+ **AWS Support:** Create a support case through the AWS Management Console for technical assistance

  Access: [AWS Support Center](https://console.aws.amazon.com/support/home)
+ **AWS re:Post:** Community-driven Q&A platform for AWS-related questions and community support

  Access: [AWS re:Post](https://repost.aws/)
+ **AWS Documentation:** Comprehensive guides for MediaTailor and CDN services

  Access: [MediaTailor Documentation](https://docs.aws.amazon.com/mediatailor/) and [CloudFront Documentation](cloudfront/)
+ **AWS Training:** Courses and certifications for media services and CDN optimization

  Access: [AWS Training and Certification](https://aws.amazon.com/training/)
+ **AWS Knowledge Center:** Curated articles for common AWS issues and best practices

  Access: [AWS Knowledge Center](https://aws.amazon.com/premiumsupport/knowledge-center/)
+ **AWS Trusted Advisor:** Automated recommendations for optimization and best practices

  Access: [AWS Trusted Advisor](https://console.aws.amazon.com/trustedadvisor/home)
+ **AWS Personal Health Dashboard:** Service health and maintenance notifications

  Access: [AWS Personal Health Dashboard](https://console.aws.amazon.com/phd/home)

## MediaTailor CDN integration support case best practices
<a name="support-case-best-practices"></a>

AWS Elemental MediaTailor CDN integration support cases are resolved more efficiently when you follow these best practices. To get the fastest resolution:
+ Choose the appropriate severity level based on business impact
+ Provide all relevant information in your initial case submission
+ Include specific examples and reproduction steps
+ Attach relevant log files and configuration screenshots
+ Respond promptly to support engineer requests for additional information

**Additional support resources:**
+ [AWS Support case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html) - Guide to creating and managing support cases
+ [AWS Support plans](https://aws.amazon.com/premiumsupport/plans/) - Compare support plan features and response times
+ [Prepare to support workloads](https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/prepare-to-support-workloads.html) - Well-Architected guidance for operational readiness
+ [AWS Well-Architected Framework](https://aws.amazon.com/architecture/well-architected/) - Best practices for building and operating workloads on AWS