惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
博客园_首页
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
博客园 - 司徒正美
有赞技术团队
有赞技术团队
Engineering at Meta
Engineering at Meta
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
API Design Patterns for Cloudflare Workers: Minimal, Secu...
Ugur Aslim · 2026-06-17 · via DEV Community

Ugur Aslim

API Design Patterns for Cloudflare Workers: Minimal, Secure, Fast

I've built APIs on every platform—traditional servers, Lambda, containers. But Cloudflare Workers fundamentally changed how I think about API design. Not because they're faster (they are), but because every millisecond saved at the edge compounds across millions of requests, and your infrastructure bill actually reflects that.

The problem: most API guidance assumes you're running a traditional backend. Cloudflare Workers demand a different mindset. You're not optimizing for throughput in a data center—you're optimizing for response time measured in tens of milliseconds, from a location physically closest to your user. That changes everything about how you validate, authenticate, and respond.

Why Edge-First Matters

Latency isn't just a performance metric. It's a reliability and cost metric.

When I migrated CitizenApp's authentication layer to Workers, response times dropped from 150ms to 18ms globally. That's not a typo. But the real win: I eliminated an entire load balancer and database replica. One request that used to hit three services now hits one at the network edge. Infrastructure costs fell 40%.

The catch: you can't think like you're building a monolith. Workers have constraints—10GB memory limit, 30-second execution timeout, limited CPU for heavy computation. You need to be surgical about what you validate, where, and what you defer.

The Core Pattern: Validation Before Logic

I prefer aggressive validation at the edge. Not because it's trendy, but because rejecting invalid requests at the edge saves downstream resources.

Here's my foundation for every Worker:

import { Router } from 'itty-router';
import { json, error } from 'itty-router-extras';

interface ValidationSchema {
  parse: (data: unknown) => Promise<unknown>;
}

const router = Router();

// Middleware: parse and validate
const validate = (schema: ValidationSchema) => {
  return async (request: Request) => {
    try {
      const body = await request.json();
      const validated = await schema.parse(body);
      (request as any).validated = validated;
    } catch (err) {
      return error(400, { error: 'Validation failed', details: err });
    }
  };
};

router.post(
  '/api/users',
  validate(userCreateSchema),
  async (request: Request) => {
    const data = (request as any).validated;
    // Proceed with validated data
    return json({ success: true, data });
  }
);

export default router;

Why this approach? Because invalid requests fail fast at the edge, never reaching your origin. On CitizenApp, this single pattern reduced origin load by 23%. That matters when you're paying per execution.

Authentication: Token Validation at the Edge

JWT validation is fast. Do it at the edge.

import { jwtVerify } from 'jose';

const SECRET = new TextEncoder().encode(
  (globalThis as any).JWT_SECRET || 'dev-secret'
);

const verifyAuth = async (request: Request): Promise<{ userId: string } | null> => {
  const authHeader = request.headers.get('authorization');
  if (!authHeader?.startsWith('Bearer ')) {
    return null;
  }

  try {
    const token = authHeader.slice(7);
    const verified = await jwtVerify(token, SECRET);
    return { userId: verified.payload.sub as string };
  } catch {
    return null;
  }
};

router.post(
  '/api/protected',
  async (request: Request) => {
    const auth = await verifyAuth(request);
    if (!auth) {
      return error(401, { error: 'Unauthorized' });
    }

    // auth.userId is now safe
    return json({ authenticated: true, userId: auth.userId });
  }
);

I've seen teams validate JWTs at the origin. That's throwing away free computation. The edge is literally built for this. Validate tokens before you touch origin infrastructure.

CORS Done Right (Not Wrong)

Most CORS implementations are theater. Here's what actually matters:

const corsHeaders = (origin: string | null): Record<string, string> => {
  // Allowlist approach—safer than wildcard
  const allowed = ['https://app.example.com', 'https://admin.example.com'];

  if (!origin || !allowed.includes(origin)) {
    return {};
  }

  return {
    'Access-Control-Allow-Origin': origin,
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    'Access-Control-Max-Age': '86400',
  };
};

router.options('*', (request: Request) => {
  return new Response(null, {
    headers: corsHeaders(request.headers.get('origin')),
  });
});

router.all('*', async (request: Request, ...args: any[]) => {
  const response = await (router as any).handle(request, ...args);
  const origin = request.headers.get('origin');

  Object.entries(corsHeaders(origin)).forEach(([key, value]) => {
    response.headers.set(key, value);
  });

  return response;
});

Why allowlist? Because CORS wildcards are a false sense of security. An attacker can still send credentials, and you've given them permission. Be explicit.

Rate Limiting: Durable Objects for State

Cloudflare Durable Objects are underrated for this use case.

export class RateLimiter {
  state: DurableObjectState;
  env: Env;

  constructor(state: DurableObjectState, env: Env) {
    this.state = state;
    this.env = env;
  }

  async check(key: string, limit: number, windowSeconds: number): Promise<boolean> {
    const data = await this.state.storage.get<{ count: number; resetAt: number }>(key);
    const now = Date.now();

    if (!data || now > data.resetAt) {
      await this.state.storage.put(key, { count: 1, resetAt: now + windowSeconds * 1000 });
      return true;
    }

    if (data.count < limit) {
      data.count++;
      await this.state.storage.put(key, data);
      return true;
    }

    return false;
  }
}

// In your route
const limiter = env.RATE_LIMITER.get('global');
const allowed = await limiter.check(auth.userId, 100, 60);

if (!allowed) {
  return error(429, { error: 'Rate limit exceeded' });
}

This isn't free—Durable Objects cost per request. But for authentication endpoints and sensitive operations, the security and control are worth it. I've seen brute force attempts destroyed at the edge for pennies.

Gotcha: Cold Starts and Warm Requests

Here's what burned me: I assumed Worker performance was consistent. It's not.

First request after deployment? 40-60ms. Subsequent requests? 8-12ms. The difference is Isolate startup. For most use cases, this doesn't matter. But if you're chaining multiple Workers or have strict SLA requirements, you need to benchmark against the realistic scenario: a cold start.

My fix: implement request coalescing for expensive operations and use cron triggers to keep Workers warm in staging.

// Warm-up cron
export async function scheduled(event: ScheduledEvent, env: Env) {
  await env.API.fetch('https://your-worker.com/__health');
}

The Takeaway

Edge-first API design isn't about using the newest technology. It's about understanding that your infrastructure cost and your latency profile are tightly coupled. Validate early, authenticate at the edge, and defer heavy computation to origin infrastructure.

I prefer Cloudflare Workers over Lambda for APIs because they force you to think about every millisecond. And thinking clearly about latency makes you think clearly about everything else.