Skip to main content
📈Scalability

Edge Computing: Processing Data Closer to Users

Edge computing moves computation and data storage closer to where it is needed — at the network edge, near the end users or data sources. Instead of sendin...

📖 4 min read

Edge Computing: Processing Data Closer to Users

Edge computing moves computation and data storage closer to where it is needed — at the network edge, near the end users or data sources. Instead of sending every request to a centralized cloud data center, edge computing processes requests at points of presence (PoPs) distributed globally. This reduces latency, saves bandwidth, and enables real-time processing for applications that cannot tolerate round-trip delays to a distant cloud.

Edge vs Cloud Computing

Aspect Edge Computing Cloud Computing
Location Near users (CDN PoPs, cell towers) Centralized data centers
Latency 1-20ms 50-200ms
Compute Power Limited per location Virtually unlimited
Storage Limited, cached data Unlimited
Best For Latency-sensitive, data filtering Complex computation, storage
Cost Per-request, low per invocation Per-hour/per-resource

Cloudflare Workers

Cloudflare Workers run JavaScript at over 300 edge locations worldwide. They execute in V8 isolates with sub-millisecond cold start times.

// Cloudflare Worker: API gateway with caching and routing
export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    // A/B testing at the edge
    const variant = request.headers.get("cookie")?.includes("variant=B")
      ? "B" : "A";

    // Rate limiting at the edge using KV store
    const clientIP = request.headers.get("CF-Connecting-IP");
    const rateLimitKey = `ratelimit:${clientIP}`;
    const currentCount = parseInt(await env.KV.get(rateLimitKey) || "0");

    if (currentCount > 100) {
      return new Response("Rate limit exceeded", { status: 429 });
    }

    await env.KV.put(rateLimitKey, String(currentCount + 1),
                     { expirationTtl: 60 });

    // Cache API responses at the edge
    const cacheKey = new Request(url.toString());
    const cache = caches.default;
    let response = await cache.match(cacheKey);

    if (!response) {
      response = await fetch(
        `https://origin.example.com${url.pathname}`,
        { headers: { "X-Variant": variant } }
      );

      response = new Response(response.body, response);
      response.headers.set("Cache-Control", "s-maxage=60");
      await cache.put(cacheKey, response.clone());
    }

    return response;
  }
};

AWS Lambda@Edge

Lambda@Edge runs Node.js or Python functions at CloudFront edge locations, triggered by CloudFront events (viewer request, origin request, origin response, viewer response).

# Lambda@Edge: Dynamic content at the edge
import json
import boto3

def lambda_handler(event, context):
    request = event["Records"][0]["cf"]["request"]
    headers = request["headers"]

    # Geo-based routing
    country = headers.get("cloudfront-viewer-country", [{}])[0].get("value", "US")

    if country in ["DE", "FR", "IT", "ES"]:
        # Route EU users to EU origin
        request["origin"]["custom"]["domainName"] = "eu-api.example.com"
    elif country in ["JP", "KR", "SG", "AU"]:
        # Route APAC users to APAC origin
        request["origin"]["custom"]["domainName"] = "apac-api.example.com"

    # Device-based content
    is_mobile = "Mobile" in headers.get("cloudfront-is-mobile-viewer",
                                        [{}])[0].get("value", "")
    if is_mobile:
        request["uri"] = request["uri"].replace("/page/", "/m/page/")

    return request

IoT Edge Computing

IoT devices generate massive amounts of data. Edge computing filters, aggregates, and processes this data locally before sending summarized results to the cloud.

import time
from collections import deque

class IoTEdgeProcessor:
    def __init__(self, cloud_endpoint, batch_size=100,
                 anomaly_threshold=2.0):
        self.cloud_endpoint = cloud_endpoint
        self.batch_size = batch_size
        self.anomaly_threshold = anomaly_threshold
        self.readings = deque(maxlen=1000)
        self.batch_buffer = []

    def process_reading(self, sensor_id, value, timestamp):
        self.readings.append(value)

        # Edge analytics: detect anomalies locally
        if len(self.readings) > 10:
            mean = sum(self.readings) / len(self.readings)
            std_dev = (sum((x - mean) ** 2 for x in self.readings)
                      / len(self.readings)) ** 0.5
            if abs(value - mean) > self.anomaly_threshold * std_dev:
                # Send anomaly immediately to cloud
                self.send_alert(sensor_id, value, mean, std_dev)
                return

        # Aggregate normal readings, send in batches
        self.batch_buffer.append({
            "sensor_id": sensor_id,
            "value": value,
            "timestamp": timestamp
        })

        if len(self.batch_buffer) >= self.batch_size:
            aggregated = self.aggregate(self.batch_buffer)
            self.send_to_cloud(aggregated)
            self.batch_buffer.clear()

    def aggregate(self, readings):
        values = [r["value"] for r in readings]
        return {
            "min": min(values),
            "max": max(values),
            "avg": sum(values) / len(values),
            "count": len(values),
            "time_range": [readings[0]["timestamp"],
                          readings[-1]["timestamp"]]
        }

Edge Computing Use Cases

Use Case Why Edge? Technology
Real-time gaming Sub-10ms response needed Cloudflare Durable Objects
Video streaming Bandwidth optimization CDN, Lambda@Edge
IoT data processing Volume reduction, local decisions AWS Greengrass, Azure IoT Edge
AR/VR applications Ultra-low latency rendering 5G MEC, edge GPUs
Content personalization Dynamic content without origin Cloudflare Workers, Vercel Edge
Security filtering Block attacks before they reach origin WAF at edge, bot detection

Edge computing connects to latency reduction strategies, geo-distribution, and high-traffic system design.

Frequently Asked Questions

Q: What are the limitations of edge computing?

Edge environments have limited CPU, memory, and storage. Execution time is typically capped (50ms for Cloudflare Workers, 5 seconds for Lambda@Edge on viewer events). You cannot maintain persistent connections or run long computations. Data consistency across edge locations is eventually consistent.

Q: How do I handle state at the edge?

Use edge-compatible storage: Cloudflare KV (eventually consistent key-value), Cloudflare Durable Objects (strongly consistent per object), DynamoDB Global Tables (accessed from Lambda@Edge). For session state, use signed cookies or JWTs that are verifiable at the edge without a database call.

Q: When should I NOT use edge computing?

Do not use edge computing for complex database queries, long-running computations, or operations requiring strong consistency across all locations. If your workload is CPU-intensive rather than I/O-bound, centralized cloud computing is more cost-effective. Edge works best for request routing, caching, authentication, and simple transformations.

Related Articles