Edge Computing and CDN Architecture for Global Stores
AI generated
60fps
ms
Performance · Edge Computing · CDN · Multi-Region
Edge Computing and CDN Architecture for Global Stores
Cutting Latency With Logic at the Network Edge

Global Magento stores lose revenue when every request has to travel across continents to reach the origin server. Edge functions move geolocation routing, A/B testing and image delivery to the nearest CDN node. The result is noticeably faster response times for customers in North America, Asia or Australia, without touching the core Magento logic running at the origin.

16 min read Edge Functions · Geolocation · A/B Testing · Image Transformation Magento 2.4.8 · Varnish · Global CDN

1. What edge functions and edge workers really are

An edge function (also called an edge worker) is a small piece of code that does not run on a central origin server, but directly on a CDN node close to the user, a so-called Point of Presence (PoP). Technically it is usually a V8 isolate or a WebAssembly sandbox, not a full container or virtual machine. That explains the key advantage: cold start times sit in the low single-digit millisecond range, far below classic serverless functions such as AWS Lambda running in a fixed region. The runtime is deliberately restricted: no filesystem access, no persistent state between requests, and a strict CPU time budget of often only 10 to 50 milliseconds per request.

The difference from a classic CDN is fundamental. A traditional CDN only serves static assets from a cache and forwards every dynamic request unchanged to the origin. An edge worker, on the other hand, can inspect requests, rewrite headers, generate responses and even call external APIs before a connection to the origin server is ever established. For a Magento store this means: logic that previously had to run in app/code on the origin server, such as simple redirects or header adjustments, can now execute closer to the user and without an origin roundtrip.

2. Practical use cases: A/B testing, geo-redirects and image transformation

Three use cases show the practical value of edge functions in e-commerce environments especially clearly. Geolocation redirects automatically send visitors to the correct store view based on their IP address, before the request even reaches the origin server. The country code field that most CDN providers expose directly at the edge makes an external geo-IP service unnecessary. For A/B testing, the edge worker handles bucket assignment via cookie: a visitor is randomly assigned to a variant on first contact, the assignment is persisted in a cookie, and it is evaluated consistently on every subsequent request, without the origin server ever getting involved.

The third category is image transformation at the edge: instead of pre-generating every product image in every required format, resolution and compression level, the edge service performs the transformation on the fly based on URL parameters and caches the result at that PoP afterwards. This drastically reduces the storage footprint in the Magento media directory and automatically delivers the format that fits the requesting device, for example AVIF for modern browsers and JPEG as a fallback. The following edge worker code combines geolocation redirect and A/B test bucketing in a single function.


// Edge worker: geolocation redirect + A/B test bucketing
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const country = request.cf?.country || request.headers.get('CF-IPCountry') || 'DE';

    // Region-based redirect to the correct store view
    const storeMap = { US: 'us_en', GB: 'uk_en', FR: 'fr_fr', DE: 'de_de' };
    const targetStore = storeMap[country] || 'de_de';

    if (url.pathname === '/' && !url.searchParams.has('store')) {
      const redirectUrl = new URL(`/${targetStore}${url.pathname}`, url.origin);
      return Response.redirect(redirectUrl.toString(), 302);
    }

    // Deterministic A/B bucket via cookie, assigned once per visitor
    let bucket = getCookie(request, 'ab_bucket');
    if (!bucket) {
      bucket = Math.random() < 0.5 ? 'control' : 'variant';
    }

    const response = await fetch(request);
    const newResponse = new Response(response.body, response);
    newResponse.headers.append('Set-Cookie', `ab_bucket=${bucket}; Path=/; Max-Age=2592000`);
    newResponse.headers.set('X-AB-Bucket', bucket);
    return newResponse;
  }
};

function getCookie(request, name) {
  const cookie = request.headers.get('Cookie') || '';
  const match = cookie.match(new RegExp(`${name}=([^;]+)`));
  return match ? match[1] : null;
}

Image delivery itself stays declarative in the template markup and needs no dedicated edge function at all, as long as the CDN provider supports native image transformation via URL parameters:


<!-- Edge image transformation: resize, format and quality via URL params -->
<picture>
  <source
    type="image/avif"
    srcset="https://cdn.mironsoft.de/media/catalog/product/hero.jpg?width=800&format=avif&quality=75 1x,
            https://cdn.mironsoft.de/media/catalog/product/hero.jpg?width=1600&format=avif&quality=75 2x">
  <source
    type="image/webp"
    srcset="https://cdn.mironsoft.de/media/catalog/product/hero.jpg?width=800&format=webp&quality=80 1x,
            https://cdn.mironsoft.de/media/catalog/product/hero.jpg?width=1600&format=webp&quality=80 2x">
  <img
    src="https://cdn.mironsoft.de/media/catalog/product/hero.jpg?width=800&format=jpg&quality=80"
    width="800"
    height="450"
    loading="eager"
    fetchpriority="high"
    alt="Product hero image, transformed at the edge">
</picture>

3. Edge rendering vs. origin rendering: the trade-off

Not every piece of logic belongs at the edge. The fundamental trade-off: edge rendering is extremely fast and globally distributed, but runs in a restricted environment with no access to the full Magento codebase, no database connection, no PHP interpreter and no access to the object manager. Origin rendering has full access to customer data, pricing logic, stock levels and personalized content, but is tied to a physical server location and correspondingly slower for distant users. The art lies in routing every request to the right layer, instead of blanket-delegating everything to the edge or everything to the origin.

A proven rule of thumb: anything that can be decided purely from request metadata, such as country, language, device or a cookie value, belongs at the edge. Anything that needs access to a customer account, cart, price rules or stock levels stays at the origin, or gets injected into an edge-cached HTML shell via Edge Side Includes (ESI). Magento's own full page cache already applies exactly this pattern locally: static blocks are cached, the mini cart is loaded afterward via AJAX. In a CDN architecture, the same principle is simply pushed one layer further outward, onto global PoPs instead of a local Varnish server.


<!-- Layout XML: mark block as edge-cacheable, exclude personalized block from edge cache -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product.info.main">
            <arguments>
                <!-- Fully cacheable at every edge PoP, region-agnostic -->
                <argument name="cache_lifetime" xsi:type="number">86400</argument>
            </arguments>
        </referenceBlock>

        <!-- Personalized block stays uncacheable, resolved at origin only -->
        <referenceBlock name="minicart.link" template="Magento_Checkout::cart/minicart.phtml">
            <arguments>
                <argument name="cache_lifetime" xsi:type="number">0</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

4. Cutting latency for a globally distributed customer base

Physics cannot be optimized away by software: a data packet from Sydney to Frankfurt needs roughly 140 to 160 milliseconds per direction purely from signal propagation over fiber, even under perfect network conditions. With a classic origin-only setup and a server in Germany, that means Australian customers face a round-trip time of around 300 milliseconds for the network path alone, before the server even starts processing. Add a TLS handshake, DNS resolution and several requests for assets, and it quickly adds up to over a second of pure network latency before the first pixel is even visible.

A global CDN with edge PoPs in Sydney, Singapore or Tokyo reduces that distance to a few kilometers for the first request. The TLS handshake terminates locally at the PoP, static assets are served from the local cache, and even dynamic requests benefit from an optimized backbone connection between PoP and origin that is noticeably more stable than a connection over the public internet. In practice this often cuts perceived load time for distant users by 40 to 60 percent, with no changes to the Magento application itself.

5. Multi-region architecture for Magento in practice

Magento itself is not designed for multi-master database operation across multiple regions. The MySQL database and the Elasticsearch cluster stay in one primary region, typically wherever the bulk of the order volume originates. For a multi-region architecture that means: the origin server remains centralized, but the edge layer is distributed globally. Static assets, cached category pages and product images are replicated at every PoP, while write operations such as checkout and account management continue to run through the central region, usually adding 100 to 200 milliseconds of extra latency for distant users.

Read replicas in secondary regions are only useful for Magento with caution, since most of the application logic assumes synchronous reads and replication lag can lead to inconsistent stock levels. A more pragmatic approach: the edge layer absorbs as much load as possible through aggressive caching of category pages and product detail pages, while checkout flows are deliberately marked origin-only and never terminated at the edge. The following configuration shows how a routing layer maps regions to origins and PoPs, and automatically fails over to the next healthy region.


{
  "service": "mironsoft-edge-routing",
  "regions": [
    {
      "code": "eu-central",
      "origin": "https://origin-eu.mironsoft.de",
      "edgePops": ["fra", "ams", "par"],
      "primaryFor": ["DE", "AT", "CH", "FR", "NL"]
    },
    {
      "code": "us-east",
      "origin": "https://origin-us.mironsoft.de",
      "edgePops": ["iad", "ord", "atl"],
      "primaryFor": ["US", "CA"]
    },
    {
      "code": "apac",
      "origin": "https://origin-apac.mironsoft.de",
      "edgePops": ["sin", "nrt", "syd"],
      "primaryFor": ["SG", "JP", "AU"]
    }
  ],
  "failover": {
    "strategy": "nearest-healthy-region",
    "healthCheckPath": "/health",
    "healthCheckIntervalSeconds": 15
  },
  "database": {
    "mode": "single-write-region",
    "writeRegion": "eu-central",
    "readReplicas": ["us-east", "apac"]
  }
}

6. CDN cache strategy: TTLs, surrogate keys and stale-while-revalidate

A working CDN cache strategy consistently distinguishes between the browser cache (Cache-Control) and the edge cache (Surrogate-Control, or CDN-Cache-Control depending on the provider). The browser cache should be kept short, often just a few minutes, so price changes and stock levels become visible promptly. The edge cache, by contrast, can stay valid much longer, around 24 hours for category pages, because it can be cleared instantly through targeted invalidation whenever needed, instead of waiting for the TTL to expire.

Stale-while-revalidate is the pattern that protects users from slow cache misses: the edge PoP serves the cached, slightly stale version immediately, and fetches a fresh copy from the origin in the background, updating the cache for the next request. No single user ever sees a slow origin response, even if the cache entry has technically already expired. For Magento stores with heavily fluctuating international traffic, this is the decisive difference between a consistent response time and sporadic latency spikes right after every cache invalidation.


#!/usr/bin/env bash
# Verify edge cache headers and purge a URL across all PoPs
set -euo pipefail

TARGET_URL="https://www.mironsoft.de/de_de/catalog/product/hero.jpg"

echo "Checking cache headers..."
curl -sI "$TARGET_URL" | grep -Ei 'cache-control|surrogate-control|x-cache|age'

# Surrogate-Control lets the edge cache longer than the browser cache
# Cache-Control: public, max-age=300
# Surrogate-Control: max-age=86400, stale-while-revalidate=3600

echo "Purging by surrogate key across all edge PoPs..."
curl -sX POST "https://api.cdn-provider.com/v1/purge" \
  -H "Authorization: Bearer ${CDN_API_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"surrogate_keys": ["product-1234", "category-55"]}'

echo "Done. Propagation to all PoPs typically completes within seconds."

7. Cache invalidation across multiple PoPs

The biggest operational difference between a single Varnish server and a global CDN is invalidation. With a local full page cache, a single PURGE request to one server is enough. With a CDN spanning hundreds of PoPs worldwide, the same invalidation has to propagate to every single node, which can take anywhere from a few seconds to a minute depending on the provider. Surrogate keys, also called cache tags, solve the problem of granular invalidation: instead of purging individual URLs, every response is tagged with identifiers such as product-1234 or category-55, so a price change only invalidates the affected pages globally, not the entire cache.

An instant purge is not actually instant with most CDN providers: there is almost always a small propagation delay between PoPs, during which a user in Tokyo already sees the new version while a user in São Paulo still gets the old one from cache. For price-critical content such as stock levels and discount campaigns, this delay should be explicitly factored into the test plan. In Magento this is often solved with a plugin hook on afterSave for product and price changes, which automatically sends the matching surrogate keys to the CDN's invalidation API, instead of purging manually or on a schedule.

8. Monitoring and observability at the edge

Edge functions run, by definition, distributed across hundreds of PoPs, which makes classic server monitoring with SSH access and local log files impossible. Most CDN providers instead offer aggregated metrics such as requests per PoP, error rates, CPU time consumed per invocation, and cache hit ratio by region. What matters is correlating these metrics with the existing Magento metrics, for example through a shared request ID generated at the edge and forwarded to the origin as a header, so a request stays traceable across the entire chain from PoP to database query.

For Real User Monitoring (RUM), the edge layer is ideally positioned because it sees the actual geographic distribution of the customer base without any extra tracking code. Many CDN providers ship regional latency dashboards out of the box, showing whether a performance problem lies at the origin, recognizable by high TTFB across all regions, or at a single PoP, recognizable by an isolated latency outlier in just one region. Alerts on cache hit ratio per region are worthwhile too: a sudden drop in a single region often points to a broken cache configuration or a faulty edge worker deployment for that exact PoP.

9. Edge and CDN architecture in direct comparison

The following overview summarizes the central trade-offs between origin rendering and edge rendering for an internationally oriented Magento architecture. Neither layer fully replaces the other, the recommendation column shows which layer is the better choice for which aspect.

Aspect Origin Rendering Edge Rendering Recommendation for global stores
Latency for international users 200-400 ms (transatlantic) 20-50 ms (nearest PoP) Edge for TTFB-critical content
Personalization and business logic Full access to the backend Restricted runtime, no DB access Origin for complex logic
Cache hit ratio Depends on central FPC High, replicated at every PoP Edge for static content
Compute cost under traffic spikes Server instances scale with load Pay-per-request, often cheaper Edge for highly variable traffic
Implementation complexity Familiar Magento stack New runtime, own deployment Origin for complex domain logic
Debugging and observability Full logging, Xdebug possible Limited tooling, distributed tracing needed Origin for critical troubleshooting

In practice, the most successful multi-region setups combine both layers deliberately: edge for everything that can be derived from request metadata, origin for everything that needs real access to business logic and customer data. Applied consistently, this split is the difference between a store that feels as fast in Sydney as in Frankfurt, and one that noticeably lags outside Europe.

Mironsoft

Edge computing, CDN architecture and global performance optimization for Magento stores

Ready to build a CDN architecture for a global customer base?

We analyze your current CDN and cache strategy, identify the latency bottlenecks for international users, and implement edge functions, multi-region routing and granular invalidation tailored to your Magento setup.

Edge Audit

Analysis of the existing CDN configuration and per-region latency measurement

Edge Implementation

Building edge functions for geolocation, A/B testing and image transformation

Multi-Region Setup

Routing, cache strategy and invalidation for global Magento deployments

10. Summary

Edge computing does not change Magento's core logic, it shifts a targeted slice of request processing to where the latency actually originates: as close to the user as possible. Geolocation redirects, A/B test bucketing and image transformation can be fully solved at the edge without ever contacting the origin server. For anything that needs real access to customer data, pricing logic or stock levels, the origin server remains responsible, supplemented by aggressive edge caching with granular invalidation via surrogate keys.

The decisive success factor is not the choice of a particular CDN provider, but the consistent separation between edge-capable and origin-bound logic, combined with end-to-end monitoring across both layers. Anyone who implements this architecture cleanly cuts latency noticeably for an internationally distributed customer base, without increasing the complexity of the core Magento application itself.

Edge Computing and CDN Architecture, the essentials

Edge Functions

Small functions running on CDN PoPs for geolocation redirects, A/B testing and image transformation, with no origin roundtrip at all.

Latency

Signal propagation time cannot be optimized away, but PoPs close to the user often cut perceived load time by 40 to 60 percent.

Multi-Region Architecture

Origin stays centralized for write operations, edge handles reads and static content across the globe.

Cache and Invalidation

Surrogate keys enable granular invalidation across hundreds of PoPs, stale-while-revalidate prevents latency spikes.

11. FAQ: Edge Computing and CDN Architecture for Global Stores

1What is an edge function and how does it differ from a classic serverless function?
Runs directly on a CDN node close to the user, usually as a V8 isolate with single-digit millisecond cold starts. AWS Lambda and similar run in a fixed region with noticeably longer cold starts.
2Which use cases are best suited for edge functions in e-commerce?
Geolocation redirects, A/B test bucketing, header manipulation, simple authorization and image transformation. Anything that only needs request metadata is a good fit for the edge.
3How does a geolocation redirect at the edge technically work?
The country code is exposed directly at the edge PoP through a request field or header. The edge worker matches it against a store view mapping and redirects before the origin is ever contacted.
4What is the difference between edge rendering and origin rendering?
Edge rendering: restricted environment, no DB access, but extremely fast and globally distributed. Origin rendering: full access to codebase and customer data, but tied to one server location.
5How does image transformation at the edge work?
The CDN service transforms images based on URL parameters like width, format and quality on the first request and caches the result at that PoP.
6What does a multi-region architecture for Magento actually look like?
Origin with database and Elasticsearch stays in a primary region, the edge layer replicates static assets globally, checkout stays processed centrally.
7How does cache invalidation work across multiple CDN PoPs?
Via surrogate keys: every response carries tags such as a product ID. Changes invalidate only the affected tags globally, not the entire cache.
8Is an instant purge from a CDN provider really instant?
Almost never fully. A small propagation delay between PoPs, ranging from a few seconds to a minute, is nearly always present.
9How do you meaningfully monitor edge functions in production?
Through aggregated CDN metrics per PoP and region, combined with a consistent request ID traceable from the edge to the database query.
10Does edge computing pay off for smaller Magento stores without a global customer base?
Latency gain is small for purely regional stores. Image transformation and bot filtering at the edge still bring measurable benefits regardless.