media server logo

Create a Virtual Events Platform — Setup CloudFront CDN for Live Events. Part I

Looking to stream live events effortlessly to a large audience? Combining Callaba, a streaming app, with a major CDN like CloudFront makes it easy to stream to lots of people.

Whether you’re hosting concerts, conferences, sports events, or any live gathering, the combination of Callaba and CloudFront ensures your stream is delivered quickly, reliably, cost-effectively, and to every viewer in any part of the world.

This tutorial is designed to guide you step-by-step through the process of setting up AWS CloudFront with Callaba. This is an updated 2024 version of our old tutorial : How to set up CloudFront on AWS.

Why we think it’s great 

  • Easy to configure. Our non-technical friend managed to complete the setup in just 40 minutes.
  • Worldwide delivery. CloudFront has 600+ points of presence in 100+ cities across 50+ countries.
  • CloudFront provides detailed reports about usage and viewers.

Key Benefits 

Amazon CloudFront is a content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds.

It's designed to work seamlessly with AWS services, including Amazon S3 and AWS Shield for DDoS protection. 

CloudFront specifically enhances the delivery and performance of HLS streaming:

1TB free data transfer per month

AWS offers a free tier with CloudFront, providing 1TB of data transfer each month for one year after signing up. This benefit can greatly reduce costs for new or small projects.

Learn more : 

Reducing data transfer costs

CloudFront reduces costs by caching content at edge locations, thus minimizing the need to fetch data repeatedly from the Origin server. This lowers the amount of data transferred within AWS’s internal network to CloudFront edge locations, which is cheaper than transferring data directly from EC2 to the internet.

Reducing latency

CloudFront delivers video content from the edge location closest to the user. This significantly cuts down latency and buffering, which is particularly beneficial for users far from the Origin server.

Auto-scaling

CloudFront automatically scales to manage increased traffic. Even if way more people joined the event than expected, CloudFront will automatically allocate more resources to provide stable performance and prevent server overload during spikes in viewership.

Robust security

AWS CloudFront integrates seamlessly with AWS security services, providing robust encryption and network protection. You can use your own SSL certificates or rely on AWS Certificate Manager to handle SSL/TLS certificates at no extra cost.

🚨 Be aware of the costs

AWS charges for resources in different ways — some are billed by the time they are active, while others are billed per request or per gigabyte.

Some resources incur minimal costs, around $4 per month, while others can add up to hundreds of dollars within a few weeks.

⚠️ Make sure you understand the billing method for each resource you use. 

For resources that are billed based on time, AWS does NOT monitor whether you’re actively using the resource; it simply tracks that the resource is taken from its pool. 

So as long as your EC2 instance is active i.e. “Running”, you are incurring charges.

Deactivate all resources once your tasks are completed to prevent any unexpected charges. It is the best way to avoid being charged for services you are not actually using

CloudFront's Pricing

CloudFront's pricing is based on the amount of data transferred out to the internet and the number of HTTP/HTTPS requests made.

Costs vary by geographic region, with no upfront fees or required long-term contracts. Users pay only for the content they deliver through the network, making it a cost-effective solution for businesses of all sizes.

📖 Before you begin

To follow this tutorial, you’ll need an active AWS account and a running EC2 Callaba instance. If you’re new to this and don’t yet have these set up, you should first complete the following tutorial:

This guide will help you get the necessary setup in place to successfully follow the steps outlined in this tutorial.

💪 Let’s begin

1. Our first task is to establish a permanent IPv4 DNS. 

Log into EC2 Console

● 2. Associate Elastic IP with your EC2 instance

“Elastic IP” is AWS’s terminology for a static / permanent IP address. For setting up CloudFront, you’ll need a stable, static IPv4 Public DNS, which is provided by Elastic IP.

To set up Elastic IP, read our detailed step-by-step tutorial (or simply watch the video):

💡Tip : Your instance does not need to be active (i.e. Running) during setup if it has an Elastic IP.

● 3. Copy Public IPv4 DNS of your instance and keep it on your clipboard; we’ll use it shortly.

Create CloudFront distribution

● 1. Go to Amazon CloudFront page or look it up in the console.

Click “Create a CloudFront distribution”

● 2. On the new page that opens, we’re going to adjust certain settings.

⚠️ Please do not change any settings not mentioned here (unless you fully understand what these settings are for).

Origin Domain 
Paste the Public IPv4 DNS address you copied earlier.

Enable Origin Shield
Select “Yes”.

Origin Shield Region
Select region where you launched your instance if it appears in the drop-down list. If your region is not listed, please refer to the table provided in our screenshot below to determine the appropriate region to select.

● 5. Scroll down to “Viewer” section

Viewer protocol policy

⚠️️ This setting will be different, depending on whether or not you’re planning to set up your own domain name and connect it to CloudFront.

  • If you are NOT going to set your own domain — Select HTTP and HTTPS
  • If you are going to do it — Select Redirect HTTP to HTTPS

Allowed HTTP methods
Select “GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE”

● 6. In the “Cache key and origin requests” section

Select Cache policy and origin request policy (recommended)

Cache Policy
 Select CachingOptimized

Origin Request Policy
Select AllViewer

Scroll down to the end of the page
Click “Create distribution”

● 7. Great job! Your CloudFront distribution is now being deployed. On the following page, you will see the domain name generated for you by CloudFront. 

It will look something like this: 
https://d1p7hgb84cngl.cloudfront.net 

(⚠️️This is just an example; your actual CloudFront domain name will be different).

Your Origin server (e.g., your Callaba AWS instance) will be accessible through this CloudFront domain. 

In the “Last Modified” column, you’ll initially see the status as “Deploying.” Please wait until this status changes to the date of the last modification.

✖ Disabling / Deleting CloudFront Distribution

As a reminder, make sure to disable or delete your distribution when it’s no longer needed. Please note that you can only delete a distribution that has already been disabled.

To disable a distribution:

  • Select the distribution you want to manage.
  • Click on “Disable.

Once the distribution is disabled, you can proceed to delete it.

Good job! First major part of the tutorial is now done.

Create a Lambda Function for security updates

🔹 What is AWS Lambda?

AWS Lambda is a serverless computing service that lets you run code without managing servers. You only pay for the compute time you use, with no costs when your code isn’t running. Lambda handles all aspects of running and scaling your code with high availability. It can be triggered automatically by other AWS services or directly from web or mobile apps.

🔹 What are we going to use Lambda for

We will create a Lambda function designed to automatically update security groups for Amazon CloudFront IP ranges. 

In simpler terms, it will provide our instance with updated lists of IP addresses belonging to CloudFront. 

This function acts like a bouncer who continuously and automatically receives updates to the guest list, ensuring that only members of the “CloudFront club” are allowed in.

📚 Read original article on AWS Blog: Automatically update security groups for Amazon CloudFront IP ranges using AWS Lambda

🔹 Why do we need to automate this?

AWS regularly updates IP ranges and without an automated update mechanism, outdated IP ranges could lead to access issues, such as 504 errors for your users. 

Automating this update process with Lambda ensures continuous access and security compliance. It is also vital for protecting your Origin from unauthorized access and potential overloads.

Learn More:

By the end of this setup, your CloudFront integration will operate smoothly, maintaining robust security and accessibility for your viewers.

Create IAM Policy & Role

To start, you’ll need to create a Policy and a Role executing said Policy for your Lambda function. This Role will specify and limit what resources our Lambda function can access and what actions it can perform, ensuring it operates within secure boundaries.

● 1. Open Identity and Access Management (IAM) Console. 

Ensure the account you use has administrator rights.

Navigate to “Policies.”

Click on “Create Policy.”

● 2. Open JSON tab

Copy the code below and paste it into the JSON tab

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CloudWatchPermissions",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Sid": "EC2Permissions",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeSecurityGroups",
        "ec2:AuthorizeSecurityGroupIngress",
        "ec2:RevokeSecurityGroupIngress",
        "ec2:CreateSecurityGroup",
        "ec2:DescribeVpcs",
        "ec2:CreateTags",
        "ec2:ModifyNetworkInterfaceAttribute",
        "ec2:DescribeNetworkInterfaces"
      ],
      "Resource": "*"
    }
  ]
}

Click “Next”

● 3. In the next page that opens

Name
Create a name for your policy (it should be specific and you have to be able to remember it), for example LambdaExecutionRolePolicy_updateCloudFrontSecurityGroups

Description
Add description for your Policy

Click “Create policy”

● 4. Navigate to Roles

Click “Create role”

Select “AWS Service”

Under Service or use case

Use case : Lambda

Click “Next”

● 5. In the “Add Permissions” page use the search bar to find the name of the policy you’ve just created (in our case the name is LambdaExecutionRolePolicy_updateCloudFrontSecurityGroups) and tick the checkbox next to it

Click “Next”

● 6. In the “Name, review, and create” page

Role name
Create a name for your role.
Name has to be specific and memorable, in our case the name is LambdaExecRole-updateCloudFrontSecurityGroups.

Scroll down to the end of the page.

Click “Create role”

Create Lambda function

With our Role and Policy ready, we’ll now create a Lambda function to implement the policy.

● 1. Change your AWS console region to US East (N. Virginia). 

This is the default region for Lambda functions, regardless of where your instance is located. Don’t worry, we’ll assign the function to your preferred region shortly.

● 2. Navigate to the Lambda console or use the search function to find it.

In the Lambda console, go to Functions

Click “Create function”

On the next page

Creation Method
Select “Author from scratch”

Function Name
Assign a specific and recognizable name to your function. For example, use CloudFront_UpdateSecurityGroups

Runtime
Choose Python 3.8 as the runtime environment.

Execution Role

Expand the “Change default execution role” settings.

  • Choose “Use an existing role”
  • Select the name of the role you previously created.

Click “Create function” 

● 3. Next, switch to the Code tab.

Copy the code using the link below and paste it into the lambda_function.py tab:

https://onecompiler.com/python/424u87m48

Click “Deploy”

● 4. Open Configuration tab

Go to General configuration

Click “Edit”

In the page that opens, 

Change Timeout to 10 seconds

Click “Save”

● 4. Now we are going to assign our function to our desired region.

Open Environmental variables

Click “Edit”

Click “Add environmental variable”

Key : REGION

Value : AWS id of your desired region (the one where your instance is in)
To find out the correct id, please refer to the table. The table is scrollable. The data you need is in the Region column.

In our example the region name is Europe (Ireland) and the region id is eu-west-1.

Click “Save”

Make sure your end result looks like this.

Test your Lambda function

● 1. Switch to the Test tab 

Select Create new event to configure a test scenario.

Event Name
Give your event a name. In this example, let’s name it TriggerSNS.

Event Sharing Settings
Set to Private

Event JSON
Copy and paste the following JSON into the Event JSON field.

{
    "Records": [
        {
            "EventVersion": "1.0",
            "EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
            "EventSource": "aws:sns",
            "Sns": {
                "SignatureVersion": "1",
                "Timestamp": "1970-01-01T00:00:00.000Z",
                "Signature": "EXAMPLE",
                "SigningCertUrl": "EXAMPLE",
                "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
                "Message": "{\"create-time\": \"yyyy-mm-ddThh:mm:ss+00:00\", \"synctoken\": \"0123456789\", \"md5\": \"7fd59f5c7f5cf643036cbd4443ad3e4b\", \"url\": \"https://ip-ranges.amazonaws.com/ip-ranges.json\"}",
                "Type": "Notification",
                "UnsubscribeUrl": "EXAMPLE",
                "TopicArn": "arn:aws:sns:EXAMPLE",
                "Subject": "TestInvoke"
            }
        }
    ]
}

This code simulates an SNS (Simple Notification Service) notification similar to what the function might receive during operation.

Click “Save”
Click “Test”

 

● 2. Handling the Error Message

After testing, you’ll see an error message. This is by design, it’s okay.

Click “Details” to view the error message.

From the error message, copy the first MD5 hash value displayed.

● 3. Edit Test event

Click “Format JSON”.

Replace the MD5 hash in the JSON with the one you just copied. 

For example, we’ve changed the MD5 value from 7fd59f5c7f5cf643036cbd4443ad3e4b to 13da9963cffcd98ba3b0d94c02ee1444.

Click “Save”

Click “Test” again

This time, it should execute successfully.

Configure Security Groups

● 1. Open the EC2 Console

Make sure you have your desired region selected (in our case it’s Ireland)

Navigate to “Security Groups”

You will see new security groups created by the function. These security groups can be easily identified as their names start with AUTOUPDATE.

The function created these security groups and put maximum possible number of rules into each group.

If you can see these AUTOUPDATE Security Groups — you’re doing everything correctly.

● 2. Navigate to “Instances” and select the instance you want to update.

Click Actions > Security > Change security groups

On the security settings page, use the search bar to find your new security groups.

Click “Add security group” after selecting each group you want to add.

Once all new security groups have been added, click “Save” to apply the changes.

● 3. Return to the EC2 Console and your instance.

Click on your instance and then select Security tab below.

Click on the security group name that does NOT have “AUTOUPDATE” in it.

You’ll be directed to the security group’s overview page.

Click Actions > Edit inbound rules

  • Delete existing rules for Port ranges 22 and 80.
  • Create new rules for Port ranges 1935 and 1945.

Click the “Add rule” button at the bottom.

Create new rules :
Custom UDP — Port range 1935 — 0.0.0.0/0
Custom TCP — Port range 1945 — 0.0.0.0/0

Click “Save” to apply the changes.

✖ Deleting Lambda Function

  • Remember to delete your Lambda function when it’s no longer needed.
  • Navigate to your function in the Lambda console, select it, and then click Actions > Delete.

🔅 Congratulations! You’ve completed the second part of this tutorial on using AWS Lambda. Now you’re ready to move on to the last section.

Configure Lambda’s trigger via AWS CLI

🔹 What is AWS CLI?

The AWS Command Line Interface (AWS CLI) is an open source tool that enables interacting with AWS services using commands in your command-line shell.

Install AWS CLI

The installation steps for the AWS CLI vary depending on your operating system. 

Follow the detailed instructions applicable to your system (Windows, MacOS, Linux) in the official guide: 

For Windows users we suggest checking out video tutorial made by “Be A Better Dev” Youtube channel : 

Get access to AWS services via CLI

Now that we’ve installed AWS CLI, we have to create access keys to be able to send commands to AWS.

● 1. Log in to the AWS Management Console

● 2. Click onto your username and select Security credentials

Click on your username at the top right corner and select Security Credentials from the dropdown menu.

Click "Create access key"

“Continue to create access key” —  tick the checkbox.

Click “Create Access Key”

In the next page, click “Download .csv file”

Keep this file somewhere safe. If you lose it, you’ll have to delete your key and generate a new one.

Set up AWS CLI and configure Lambda function triggers

● 1. Configure AWS CLI

Open the Terminal on your PC.

Type aws configure command. This will prompt you to enter four pieces of information:

  • Access key ID
  • Secret access key
  • AWS Region
  • Output format

Here’s an example of how to input these values:

$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json

For a more detailed guide on AWS CLI configuration, refer to 🔗 Configuration basics.

● 2. Connect Lambda function to SNS

Open your Lambda function in the AWS Management Console

Locate and copy Amazon Resource Name (ARN) or click “Copy ARN”

● 3. Subscribe Your Lambda Function to an SNS Topic

Replace YOUR_LAMBDA_ARN with the ARN you copied from your Lambda function in the command below.

aws sns subscribe --topic-arn "arn:aws:sns:us-east-1:806199016981:AmazonIpSpaceChanged" --region us-east-1 --protocol lambda --notification-endpoint "YOUR_LAMBDA_ARN"

Execute the command.

● 4. Grant SNS permission to invoke your Lambda function

Replace YOUR_LAMBDA_ARN with your copied ARN in the following command:

aws lambda add-permission --function-name "YOUR_LAMBDA_ARN" --statement-id lambda-sns-trigger --region us-east-1 --action lambda:InvokeFunction --principal sns.amazonaws.com --source-arn "arn:aws:sns:us-east-1:806199016981:AmazonIpSpaceChanged"

Execute the command.

Now your setup is complete. Congratulations!

Use your CloudFront setup

You’ve done great work, let’s figure out how to use it.

We’ve already talked about how when you set up CloudFront, you get a CloudFront domain name generated for you.

That domain name usually looks something like this :

https://d1p7hgb84cngl.cloudfront.net

(This is an EXAMPLE; you need to get your actual domain name via AWS CloudFront interface.)

Check if it works

If you’ve done everything correctly, when you turn on your instance, you’ll be able to use this CloudFront domain to access Callaba dashboard.

Video streaming

To video stream via CloudFront, you can replace IP address within the URL of your video player with your CloudFront domain name.

⚠️ We, however, stronly recommend attaching your own domain name in this case. 

https://d1p7hgb84cngl.cloudfront.net/vod-player/65527a127a30994bdf8685a8

Video embedding

When inserting your widget, please replace the IP address within the URL with your CloudFront domain name.

Like this :

<iframe width=”560" height=”315" src=”https://d1p7hgb84cngl.cloudfront.net/vod-player/65fd6d907c93e071972114d2?embedEnabled=true&amp;playerEnabled=false" title=”Video player” frameborder=”0" allow=”accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture” allowfullscreen=””></iframe>

(This is also an EXAMPLE code)

This concludes first part of our tutorial on AWS CloudFront. In our next tutorial we’re going to explain how to attach your own domain name to CloudFront.

If you have any questions, you can contact us at [email protected], and we’ll respond within 48 hours.

Happy streaming!