Serverless Edge Functions: Build and Deploy with Cloudflare

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Serverless Edge Functions: Build and Deploy with Cloudflare
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

In production, we often encounter a situation: a standard server cannot handle peak loads, and spinning up a cluster for a couple of endpoints is like shooting sparrows with a cannon. Cloudflare Workers solve this problem: code runs on V8 isolates with a cold start of less than 1 ms on 300+ edge nodes. According to Cloudflare Workers documentation, the cold start is under 1 ms. The free tier covers 100,000 requests per day — enough for most projects. Our experience integrating Workers on dozens of sites shows: fault tolerance increases, and infrastructure costs drop by 40-60% compared to traditional solutions. For a project with 500k requests per month, this saves up to $200 monthly. Worker pricing starts at $5 per month for 10 million requests, making it affordable for startups.

Cloudflare Workers achieve cold start under 1 ms

Workers run on Cloudflare Workers technology with V8 isolation, where each Worker runs in a separate V8 context. Unlike containers, V8 isolates do not require loading an OS or runtime — the code is compiled and executed instantly. This gives a cold start <1 ms, while AWS Lambda takes 500-2000 ms due to container initialization. Cloudflare Workers cold start is up to 2000 times faster than AWS Lambda. For example, Workers handle requests 100 times faster on first launch, which is critical for low-latency APIs. With our 5 years of experience and over 100 projects, we guarantee reliable implementation.

Comparison with AWS Lambda and Vercel Functions

Workers run in every Cloudflare PoP — a user from Moscow gets a response from the nearest node, not from us-east-1. This is fundamental for latency-sensitive tasks. Limitation: Workers use Web API, not Node.js API — fs, child_process, native modules are unavailable. But there is no cold start like Lambda (where it can reach several seconds with default settings). Vercel Functions also have delays — they rely on containers. Workers on V8 isolates win in initialization speed.

When to Use Workers vs Traditional Backend

If your site requires low latency for API requests, geo-distribution, or integration with external services — Workers are the obvious choice. A full server is recommended when you need long connections to PostgreSQL, work with large files, or complex CPU calculations. For everything else, Workers are a lightweight and cheap alternative.

Basic Worker
// src/index.ts
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/api/contact" && request.method === "POST") {
      return handleContact(request, env);
    }

    if (url.pathname === "/api/geo") {
      return handleGeo(request);
    }

    return new Response("Not found", { status: 404 });
  },
};

async function handleContact(request: Request, env: Env): Promise<Response> {
  const data = await request.json<{ name: string; email: string; message: string }>();

  // Send via Resend API
  const emailResponse = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${env.RESEND_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: "site@YOUR_DOMAIN",
      to: ["team@YOUR_DOMAIN"],
      subject: `Message from ${data.name}`,
      text: `${data.name} (${data.email}): ${data.message}`,
    }),
  });

  if (!emailResponse.ok) {
    return Response.json({ error: "Email send failed" }, { status: 500 });
  }

  return Response.json({ ok: true });
}

// Geolocation from Cloudflare headers
function handleGeo(request: Request): Response {
  const cf = (request as any).cf;
  return Response.json({
    country: cf?.country,
    city: cf?.city,
    timezone: cf?.timezone,
    latitude: cf?.latitude,
    longitude: cf?.longitude,
  });
}

Wrangler and deployment

Deployment steps:

  1. Install Wrangler CLI: npm install -g wrangler
  2. Authenticate: wrangler login
  3. Write your Worker code in src/index.ts
  4. Configure wrangler.toml with your settings
  5. Deploy: wrangler deploy
Wrangler Configuration Example
# wrangler.toml
name = "my-site-api"
main = "src/index.ts"
compatibility_date = "2024-11-01"

[vars]
ENVIRONMENT = "production"

[[routes]]
pattern = "YOUR_DOMAIN/api/*"
zone_name = "YOUR_DOMAIN"
npm install -g wrangler
wrangler login
wrangler dev          # local development
wrangler deploy       # deploy

Secrets:

wrangler secret put RESEND_API_KEY
wrangler secret put DATABASE_URL

Workers KV and D1: data storage at the edge

KV is a key-value store, eventually consistent. Suitable for cache, sessions, configuration. Workers KV provides edge acceleration for data access.

KV Example
// Bind in wrangler.toml
// [[kv_namespaces]]
// binding = "CACHE"
// id = "abc123..."

export default {
  async fetch(request: Request, env: Env & { CACHE: KVNamespace }) {
    const cacheKey = new URL(request.url).pathname;
    const cached = await env.CACHE.get(cacheKey);

    if (cached) {
      return new Response(cached, {
        headers: { "Content-Type": "application/json", "X-Cache": "HIT" }
      });
    }

    const data = await fetchFreshData(request);
    await env.CACHE.put(cacheKey, JSON.stringify(data), { expirationTtl: 300 });

    return Response.json(data);
  }
};

D1 is Cloudflare's serverless SQLite database. Suitable for small data volumes (up to 10 GB). With serverless computing, D1 scales automatically without management overhead.

D1 Example
export default {
  async fetch(request: Request, env: Env & { DB: D1Database }) {
    const { results } = await env.DB.prepare(
      "SELECT * FROM products WHERE category = ? ORDER BY created_at DESC LIMIT 20"
    ).bind("electronics").all();

    return Response.json(results);
  }
};

Working with data and limitations

  • CPU time: 10 ms (free), 30 s (Paid)
  • Memory: 128 MB
  • No Node.js built-ins (fs, path, crypto — only Web Crypto API)
  • No long-lived connections to PostgreSQL (use Hyperdrive or HTTP API)

Hyperdrive solves PostgreSQL connection problem

Hyperdrive proxies connections to an external PostgreSQL database through a connection pool on the Cloudflare side, solving the latency issue of connecting to a remote DB. This allows Workers to work with relational databases without delays in establishing new connections.

Performance comparison: Workers vs AWS Lambda vs Vercel Functions

Parameter Cloudflare Workers AWS Lambda Vercel Functions
Cold start <1 ms 500-2000 ms 100-500 ms
Geo-distribution 300+ PoP 30+ regions per deployment region
Max CPU 30 s 15 min 60 s
Free limit 100k requests/day 1M requests/month 100k requests/month

Workers significantly win in cold start and global availability. Building an API on Cloudflare ensures low latency worldwide.

Storage options comparison

Service Type Use Case Consistency
Workers KV Key-value Cache, sessions Eventual
D1 SQLite Small relational data Strong
Hyperdrive Proxy External PostgreSQL Strong (via DB)

What's included in the work

When ordering Workers development, you get:

  • Architecture design and selection of optimal services (KV, D1, Hyperdrive)
  • Implementation of all endpoints with error handling and timeouts
  • CI/CD with GitHub Actions and automatic deployment via Wrangler
  • Documentation for operation and description of all environment variables
  • Load testing up to 1000 RPS with subsequent optimization
  • Team training on Cloudflare Dashboard and Wrangler CLI

Timeline

Basic Worker with routing and 3-5 endpoints — from 2 to 3 days. Integration of KV and D1, CI/CD via GitHub Actions — plus 2 days. Full solution with Hyperdrive and custom domains — up to a week. Contact us for an accurate estimate of your project.

Why Serverless Development? The Real Economics and Technical Trade-offs

Serverless does not mean "without servers". Servers exist—you just don't manage them. It's more accurate to think of it as "without server management": no OS patching, no nginx configuration, no disk space monitoring. The function receives an event, processes it, and returns a response. The provider decides where to run it. Мы занимаемся serverless-архитектурой более 5 лет и реализовали 30+ проектов на AWS Lambda, Vercel Functions и Cloudflare Workers. Гарантируем, что ваша система масштабируется без переплат — при условии правильного выбора платформы и оптимизации холодного старта.

Platform Cold Start (Node.js) State Management Bundle Size Limit Best For
AWS Lambda 200ms–1.5s (VPC: до 10s) External (DynamoDB, S3) 250MB (with layers) Complex event‑driven, enterprise
Vercel Functions ~300ms (50ms with Edge) Edge Config, KV 4MB (Edge), 50MB (Serverless) Next.js, JAMstack, middleware
Cloudflare Workers <1ms Durable Objects, KV, D1 1MB (worker code) Global low‑latency, real‑time

Cold start — Lambda's main pain point on Node.js. In VPC, cold start reached 10 seconds before recent improvements. For production functions with latency requirements: Provisioned Concurrency (keeps instances warm), SnapStart for Java, minimize bundle via tree-shaking. Our typical optimization reduces cold start from 3.2s to 400ms.

Practical case: an image processing function (resize, WebP conversion, upload to S3). Bundle with sharp was 40MB due to native binaries. Solution: Lambda Layer with sharp, main function 800KB. Cold start dropped from 3.2s to 400ms. Lambda Layers — shared dependencies between functions. Up to 5 layers per function, each up to 250MB. Standard practice: layer with heavy dependencies (sharp, puppeteer, ffmpeg), layer with common business logic. Infrastructure for Lambda via AWS CDK or Terraform. SAM — for beginners, CDK — for serious projects with type safety.

Edge Runtime is fundamentally different: the function runs on a V8 isolate in the nearest Vercel CDN point (120+ regions). No cold start as such — the isolate starts in ~0ms. But strict limitations: no Node.js API (fs, crypto via Web API), no database access via TCP (only via HTTP API), bundle size up to 4MB. Edge Runtime is ideal for: middleware (auth check, redirect, A/B test), response transformations, geolocation logic, Edge Config. Not suitable for: accessing PostgreSQL, heavy computations, file system operations.

Cloudflare Workers run on V8 isolates in 300+ points of presence. Latency for the user is literally the nearest data center. Cold start < 1ms. Workers Durable Objects solve the state problem at the edge: each Durable Object is a single coordination point, running in one region. Ideal for: game rooms, real-time documents, rate limiting without races. Workers KV — eventually consistent storage. Writes propagate to all regions in ~60 seconds. Not suitable for financial transactions, suitable for configs, feature flags, cache. D1 — SQLite on the edge. Works great on a single read replica, write latency depends on distance to primary region. Not ideal for global write-heavy applications.

Ecosystem: Hono.js — a minimalist router that works on Workers, Deno, Bun, Node.js. Good choice if you need unified code for edge and server.

Vendor lock-in — a real problem. Lambda-specific code (handler signature, Lambda context) is hard to port. Hono.js, Remix, or adapters like @hono/node-server help keep logic portable. Мы проектируем абстракции, позволяющие сменить провайдера с минимальными изменениями.

How We Optimize Cold Start in AWS Lambda?

Cold start is Lambda's worst enemy. Here’s a step‑by‑step optimisation checklist we apply:

  1. Minimise bundle size — tree‑shake dependencies, use Lambda Layers for native binaries (sharp, puppeteer). Target < 1MB.
  2. Enable Provisioned Concurrency for latency‑critical functions — costs extra but cuts cold start to near zero.
  3. Use SnapStart for Java (Lambda) — reduces init time by 90%+.
  4. Avoid VPC unless necessary — if you need VPC, use AWS PrivateLink or Elastic Network Interface optimisation.
  5. Warm‑up strategies — scheduler pinging function every 5 minutes (but only for low‑volume functions, otherwise Provisioned Concurrency cheaper).

Result: our clients typically see cold start drop from 2–4s to under 500ms. For a fintech API handling 50k requests/day, that means 3 fewer seconds of latency per request during peak scale.

When Does Serverless Not Fit? Cost Comparison

Serverless saves money when traffic is unpredictable or sparse — up to 70% reduction compared to dedicated servers. But it becomes expensive under constant high load. Example: a function processing 1 million requests/day at 300ms each costs about $100–200/month on Lambda. Equivalent EC2 instance might cost $50/month. For such steady workloads, Fargate or EC2 is cheaper.

Long computations (>15 min on Lambda, >30s on Vercel) require Fargate or a regular server. WebSocket server with state — no persistent process. Tasks with frequent disk access — ephemeral storage, /tmp on Lambda 512MB–10GB.

What’s Included in Serverless Development Service?

Мы предлагаем serverless-разработку под ключ. В каждый проект входит:

  • Архитектурная документация (схема event‑driven потоков, выбор платформы, justification).
  • Реализация функций с unit‑ и integration‑тестами.
  • CI/CD pipeline (GitHub Actions / GitLab CI) с preview‑деплоями.
  • Infrastructure as Code (Terraform / AWS CDK / Pulumi).
  • Мониторинг и observability (OpenTelemetry, structured logging, distributed tracing).
  • 30‑дневная пост‑релизная поддержка и оптимизация производительности.

Typical Mistakes in Serverless Development and How We Avoid Them

  • Ignoring cold start — we measure and budget for it from day one.
  • Over‑engineering state — many teams try to use Workers Durable Objects for simple caching; KV is often enough.
  • No distributed tracing — without trace IDs across SQS › Lambda › DynamoDB streams, debugging is blind. We integrate AWS X‑Ray or OpenTelemetry automatically.
  • Underestimating cost at scale — we simulate load patterns and compare serverless vs. container costs before committing.

Закажите serverless архитектуру под ключ — свяжитесь с нами для бесплатной оценки вашего проекта. Сроки: от 2 недель для MVP, до 10 недель для миграции монолита. Стоимость рассчитывается индивидуально, ориентировочно от $2,000 до $15,000 в зависимости от сложности.