Supercharging URL Redirects with AWS CloudFront Functions and KeyValueStore

Optimizing URLs with fast-edge redirects

At Babbel, we’re dedicated to crafting web experiences that are lightning-fast and seamless, ensuring users land on the right page in an instant whether it’s a revamped product URL or a catchy campaign link. Our goal was to transform URL redirects to preserve search engine rankings and enhance marketing campaigns with memorable vanity URLs, while allowing marketers to manage changes without developer support. We turned to AWS CloudFront Functions and KeyValueStore (KVS), paired with a custom admin UI, to bring this vision to life. Here’s our story.

The Power of AWS CloudFront Functions and KeyValueStore

Imagine a user typing babbel.com/promo into their browser and expecting an instant redirect to a campaign page. That fleeting moment unfolds at the edge of the internet, where AWS CloudFront Functions work their magic. Launched in 2021, these serverless scripts run at CloudFront’s 700+ edge locations, handling tasks like URL redirects in microseconds. Unlike Lambda@Edge, which is designed for complex logic with network access, CloudFront Functions are lightweight and focused, ideal for redirects and header tweaks. But they come with constraints: a 10KB code size limit, no external network calls, and a strict JavaScript runtime (cloudfront-js-2.0 for KVS integration). 

Then there’s CloudFront KeyValueStore, launched in November 2023, a low-latency datastore that redefined our approach. KVS lets us manage redirect mappings like /promo to /campaign/spring-sale-2025 without hardcoding them into functions. Data retrieval is near-instantaneous sub-microsecond at the edge and updates sync globally in a few seconds. It’s secure, with encryption at rest and in transit, and supports use cases like URL redirects, A/B testing, and access control. However, KVS comes with constraints: each key-value pair is limited to 1 KB, a single KeyValueStore can hold up to 5MB key-value pairs, and only one KVS can be linked to a given CloudFront Function etc. 

How Do CloudFront Functions and KeyValueStore Work?

CloudFront Functions run on a JavaScript runtime (version 2.0 for KVS integration) and are triggered by viewer request or response events. For redirects, a function typically intercepts a viewer request, processes the URL, and returns a redirect response (e.g., HTTP 301 or 302) before the request reaches the origin server. 

Here’s a simplified workflow for Babbel’s use case:

  • Viewer Request: A user requests a URL (e.g., https://www.babbel.com/old-path).
  • Function Execution: A CloudFront Function, deployed at the edge, intercepts the request.
  • KVS Lookup: The function queries the KVS using the requested URL path
  • Redirect Response: If a match is found, the function returns a 301 redirect response with the new URL. If no match exists, it passes the request to the origin.
  • Caching: CloudFront caches the redirect response (if configured), reducing subsequent lookups.

Building a Streamlined Redirect System

Our aim was to create a redirect system that could handle URL redirects for SEO and marketing while giving marketers autonomy. We began with KVS, setting up a table to store redirect mappings. When a user visits babbel.com/old-path, our CloudFront Function intercepts the request, queries KVS for the target URL (like babbel.com/new-path), and delivers a 301 redirect before the request hits our origin servers. The function, written in cloudfront-js-2.0, is optimized to stay under the 10KB limit, ensuring redirects execute in under a millisecond. 

Here’s a glimpse of the code:

import cf from 'cloudfront';

const kvsId = <kvs-Id>;
const kvsHandle = cf.kvs(kvsId);

async function handler(event) {
  const request = event.request;

  const pathSegments = request.uri.split('/');
  const requestPath = pathSegments[1].toLowerCase();

  try {
    // Fetch the redirect URL from the KV store using the request path as the key
    const redirectUrl = await kvsHandle.get(requestPath);
    console.log(redirectUrl);
    if (redirectUrl) {
      // If a redirect URL is found, return a 302 redirect response
      return {
        statusCode: 302,
        statusDescription: 'Found',
        headers: {
          location: { value: redirectUrl }
        }
      };
    } else {
      // If no URL is found, pass the request through without modification
      return request;
    }
  } catch (error) {
    // Log any errors and pass the request through if the KV store lookup fails
    console.error('Error fetching redirect URL from KV store:', error);
    return request;
  }
}

[code snippet written on: language-javascript ]

Since vanity URLs are typed and users may make case errors (e.g., PROMO vs. promo), we convert the path toLowerCase before lookup.

To make this system marketer-friendly, we built a custom admin UI integrated with the AWS SDK. This intuitive tool lets marketers list, add, update, or delete URL redirects in KVS. Updates sync globally in seconds via the KVS API, enabling rapid campaign launches without developer involvement.

Transforming Performance: SEO, Vanity URLs, and User Experience

Previously, 100ms-1s origin-based redirects slowed loads and raised bounce rates, harming SEO and user experience. Now, <100ms edge redirects – this often results in redirect performance improvements of 10x or more, and as a reminder, improved performance drives revenue, cut load times, reduced bounce rates, boosted conversions, and improved SEO with faster crawls.

Why This Matters

Our AWS CloudFront Functions and KeyValueStore journey shows URL redirects can drive user satisfaction and business value. Compressing URLs, preventing host-specific conflicts, and overcoming limits we built a fast, scalable, marketer-friendly system, delivering quick redirects, engagement, and simplicity for lasting success.

Looking for your next adventure?
Check us out!
Share: