AWS for M&E Blog
EPG-enriched ad requests with CloudFront Functions and AWS Elemental MediaTailor
As a TV streaming operator, you need to deliver contextually relevant ads based on what’s currently airing. That means knowing whether a program is live, along with details such as its genre, rating, and series. This metadata drives ad targeting decisions that directly impact revenue.
In this post, we demonstrate how to build an EPG (Electronic Program Guide) metadata enrichment pipeline using Amazon CloudFront Functions, Amazon CloudFront KeyValueStore (KVS), and AWS Elemental MediaTailor Monetization Functions. The architecture enriches every outgoing ad request with current program context while adding only around 10 ms to each ad request in FetchTV’s deployment.
This solution enriches every ad break rather than once per session, so ad requests stay accurate even when a viewer watches a linear channel for hours.
The challenge
Ad Decision Servers (ADS) perform better targeting when they understand the content context surrounding an ad break. For linear channels, this means knowing:
- Is the current program live or pre-recorded?
- What genre and rating does the program carry?
- What series, season, and episode is airing?
The challenge is twofold. First, EPG data from schedule providers is typically delivered as a large JSON payload of up to 50 KB covering an entire broadcast day. MediaTailor Monetization Functions accept a response body of up to 20,000 characters, so the architecture reduces the schedule to the current program before it reaches the ad-request path.
Second, the metadata must stay accurate for the life of the session. Linear channels are watched continuously, often for hours in the same playback session. If you resolve program metadata only at session initialization, it captures whatever was airing when the viewer tuned in. That metadata then drifts out of date as one program ends and the next begins. An ad break several programs later would carry the context of a show that finished hours ago. The enrichment therefore has to happen at each ad break, not at session start.
Architecture overview
The solution decouples EPG data ingestion from real-time ad enrichment using a pre-computation pattern.
Figure 1: EPG metadata enrichment pipeline showing off-path data synchronization (EPG API → AWS Lambda → KVS) and on-path ad enrichment (CloudFront Function → MediaTailor)
Components
- AWS Lambda (Synchronizer) – Runs on a schedule, fetches the full EPG from the schedule provider, extracts program metadata, and writes compact entries to CloudFront KeyValueStore.
- Amazon CloudFront KeyValueStore – Stores per-channel program metadata using a two-tier key structure (time-block indices and individual program entries). Provides low-latency reads at the edge.
- Amazon CloudFront Function – Runs at the edge on every ad request. Performs two KVS reads (index lookup and program metadata) to find the currently airing program and returns its metadata as a minimal JSON response (approximately 250 bytes).
- AWS Elemental MediaTailor (Monetization Function) – An
HTTP_REQUESTfunction bound to thePRE_ADS_REQUESTlifecycle hook calls the CloudFront endpoint, reads the response, and appends all metadata fields to the outgoing ADS URL.
How it works
The solution runs in two paths: an off-path job that keeps program metadata current in KVS, and an on-path lookup that runs at each ad break.
Data synchronization (off-path)
An Amazon EventBridge rule triggers the Lambda function every 6 hours (four times a day). On each run, the function does the following:
- Fetches the EPG schedule from the provider’s API.
- Extracts metadata for all programs: title, genre, rating, live status, series information, duration, keywords.
- Assigns each program to time-block index keys (3-hour windows).
- Adds each program to every block it overlaps.
- Writes entries to KVS using the batched
update_keysAPI.
KVS key structure:
All block boundaries are in UTC. On each run, the Lambda function writes program keys before index keys, so the data is in place before any pointer references it. It merges each index block rather than replacing it, keeping entries whose end time is still in the future and adding new ones. That way, a program airing during a sync survives it. It deletes only program keys whose end time has already passed. Writes go through update_keys in batches under a single ETag, which is required because the API accepts at most 50 keys or 3 MB per request.
Real-time enrichment (on-path)
When a viewer hits an ad break:
- The MediaTailor
PRE_ADS_REQUESThook fires theHTTP_REQUESTfunction. - The function calls
GET /epg-metadata?channel={id}on the CloudFront distribution. - CloudFront Function intercepts at viewer-request, reads the current block’s index from KVS.
- Finds the program where
start_ms <= Date.now() < end_ms. This solution covers live-edge playback, where the ad request and the break’s air time are effectively the same. To extend it to DVR or start-over, replaceDate.now()with a timestamp supplied by the stream or session. - Reads the program’s full metadata from KVS.
- Returns a compact JSON response:
- MediaTailor appends the mapped fields to the ADS URL:
Design decisions
The following sections explain the main choices behind this architecture.
Why CloudFront KeyValueStore?
CloudFront KVS provides globally distributed, low-latency reads directly from CloudFront edge locations, with no origin round trip.
Why not serve the schedule as JSON from Amazon Simple Storage Service (Amazon S3) behind CloudFront?
The response.body limit is 20,000 characters, and JSONata supports $filter and $millis(), so this might look viable. We chose KVS for consistent, fast response times. KVS answers every request at the edge from local data, while a cached file adds a slower tail on cache misses and after each schedule refresh. A file over 20,000 characters would also fail silently, and selection logic in JSONata is harder to unit test.
Why pre-compute instead of real-time fetch?
PRE_ADS_REQUEST shares a 2,000 ms budget with the other request-path hooks, and MediaTailor drops its output on a timeout. Fetching and parsing a full day of EPG data on every ad break would make response times vary from break to break.
Pre-computing the schedule into compact ~250-byte entries removes that variability: every request is answered at the edge from local KVS data, with no origin round trip. The result is consistent, predictable latency, with p50 9 ms, p95 15 ms, and p99 22 ms across thousands of ad breaks in FetchTV’s production deployment.
Why enrich at ad-request time instead of session initialization?
MediaTailor also supports a session initialization hook, where metadata can be resolved once when a playback session begins. This works for short-form or on-demand content, where the session covers a single asset. Linear TV requires a different approach.
Linear channels are watched continuously, often for hours. A viewer who tunes in during the morning and leaves the channel on through to the evening keeps the same MediaTailor session throughout. If the channel’s program metadata is captured only at session initialization, it reflects whatever was airing when the viewer tuned in and then goes stale as programs change. By the time an ad break fires several programs later, the ad request would carry the title, genre, and rating of a show that finished hours ago.
Resolving the metadata in the PRE_ADS_REQUEST hook runs the lookup on every ad break, so each ad request describes the program that is actually airing when the break is requested. Combined with the low-latency edge lookup, this accuracy comes at no meaningful latency cost.
Why 3-hour index blocks?
Programs are indexed in all time blocks they span, so a single KVS read always finds the current program. With eight blocks per day, each block stays well under the KVS 1 KB value limit even at maximum schedule density.
Multi-block indexing
A program airing from 16:30–21:30 UTC is indexed in blocks 5, 6, and 7. This removes the need for fallback reads across blocks. The CloudFront Function always finds the program in its current block’s index on the first read.
Field size controls
To stay within the KVS (1 KB) and MediaTailor (1,000 characters per output value) limits:
| Field | Max length |
content_title |
100 chars |
content_series |
100 chars |
content_keywords |
80 chars |
content_genre |
50 chars |
content_rating |
10 chars |
As a backstop, the Lambda function measures each program’s serialized UTF-8 byte length before writing. If an entry would exceed the KVS 1 KB value limit, the function truncates the free-text fields in order: keywords first, then series, then title. In practice, the per-field caps keep entries well under 1 KB, so this rarely triggers.
Security
The CloudFront Function validates a shared-secret header (X-Origin-Verify) on every request. The secret is held in FetchTV’s secrets manager and injected at deploy time, and requests without it receive a 403 immediately, before any KVS read. This is a lightweight check to stop unauthorized public access rather than a full security control. Because EPG data is effectively public, the main risk is cost from abusive request volume. For larger deployments, you can add AWS WAF for rate-based and managed rules, at extra cost.
Cost analysis
At 140,000 ad requests per month (public pricing as of August 2026):
| Component | Monthly cost |
MediaTailor Functions (PRE_ADS_REQUEST, ~140,000 invocations) |
~$14 |
| CloudFront Function invocations (~140,000) | ~$0.01 |
| CloudFront KVS reads (~280,000) | ~$0.01 |
| CloudFront HTTPS requests (~140,000) | ~$0.18, normally covered by the AWS Free Tier |
| Lambda (4x daily) | ~$0 (AWS Free Tier) |
| Amazon EventBridge | ~$0 (AWS Free Tier) |
| Total | ~$14/month |
Note: Pricing is based on AWS public rates and might vary with volume or enterprise agreements. CloudFront request pricing varies by geographic region. These estimates use Asia Pacific (Sydney) AWS Region rates, and Australia and New Zealand rates for CloudFront.
Deployment
You can define all of the infrastructure as code with AWS CloudFormation, using the following resource types:
AWS::CloudFront::Distribution– Distribution with Function association.AWS::CloudFront::Function– Edge function withKeyValueStoreAssociationsand header validation.AWS::CloudFront::KeyValueStore– Global edge datastore.AWS::Lambda::Function– Synchronizer with Amazon EventBridge trigger.AWS::Events::Rule– Scheduled execution (every 6 hours).AWS::MediaTailor::Function– Monetization Function (HTTP_REQUESTtype).AWS::MediaTailor::PlaybackConfiguration– Binds the function to thePRE_ADS_REQUESThook through itsFunctionMappingproperty.AWS::IAM::Role– Execution roles for Lambda and MediaTailor.
CloudFormation supports each of these resources, including the MediaTailor Monetization Function and its lifecycle hook binding, so you can deploy and manage the entire solution as a single CloudFormation stack.
Results
In FetchTV’s production deployment, every ad break request carries full EPG context:
- 100 percent enrichment rate – Across approximately 14,000 ad breaks over three days, with no missed programs at block boundaries.
- p50 9 ms, p95 15 ms, p99 22 ms for the MediaTailor function to call CloudFront and receive the response.
- Zero origin load – All data served from edge, EPG API called only four times daily.
- Graceful degradation – If the function fails or times out, the ad request fails open. MediaTailor sends the ADS request unmodified. Because these failures are silent, monitor the MediaTailor function logs for breaks sent without metadata.
Conclusion
By combining CloudFront Functions, KeyValueStore, and MediaTailor Monetization Functions, you can enrich every ad request with real-time EPG metadata at negligible cost and minimal added latency. The architecture can support dozens of channels per key value store, with edge infrastructure costs under $2/month. The main cost grows with ad request volume rather than channel count.
The pattern is extensible. You can add more metadata fields, such as audience segments or sponsorship flags, to KVS entries without architectural changes. The same endpoint serves all channels through a single CloudFront distribution.
To test this pattern, you need a MediaTailor playback configuration with ad insertion. If you don’t have one, you can quickly deploy an end-to-end live streaming workflow using the Live Event Framework. Next, create your own CloudFront Function and KeyValueStore. Then use the MediaTailor console to create an HTTP_REQUEST function that calls your CloudFront endpoint, and attach it to the Ad request hook.