InertiaRSS Track and read blogs, news, and tech you care about
Read Original Open in InertiaRSS

Recommended Feeds

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
A
About on SuperTechFans
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
G
Google Developers Blog
博客园_首页
云风的 BLOG
云风的 BLOG
Engineering at Meta
Engineering at Meta
博客园 - 叶小钗
The Cloudflare Blog
博客园 - 三生石上(FineUI控件)
GbyAI
GbyAI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
WordPress大学
WordPress大学
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell

博客园 - iTech

7万星的AI交易框架:让大模型模拟投行多空辩论,自动做交易决策 71000颗星的AI交易团队:让大模型模拟投行分工,自动做交易决策 13400颗星的开源项目:输入一句话,AI全自动帮你做短视频 102颗星的沙盒:当AI学会自己写代码、跑测试、做部署 AI 技术日报 - 2026-05-08 29k 星的 PageIndex:不用向量数据库,靠推理就能做 RAG 每天花两小时刷信息?这个开源项目帮你全自动搞定 读源码像读小说?试了 DeepWiki 和 Zread,我再也不想裸读 GitHub 了 Matt Pocock 开源的这套 .claude 技能,为什么让工程师集体上头? Cursor Team Kit:Cursor 官方团队在用的 17 个 AI 工作流 AI 技术日报 - 2026-05-07 AI 技术日报 - 2026-05-06 AI 技术日报 - 2026-05-05 Anthropic CEO 说 12 个月内程序员要失业,我扒完他的底牌,发现事情没那么简单 把工程师的肌肉记忆装进 Claude Code,这个 4300 Star 的项目我后悔没早用 AI 技术日报 - 2026-05-04 AI 技术日报 - 2026-05-03 AI 技术日报 - 2026-05-02 六大 Agent 框架横评:谁支持 Skills?谁能自动创建 Agent?MCP 呢? Wechatsync:一个 Chrome 插件,一键把文章同步到 31 个平台 LangChain 开源了 Open SWE:Stripe、Ramp、Coinbase 内部都在造的编程 Agent Cockpit:把 Claude Code 从终端里搬出来,装进浏览器 Cursor 把自家的 AI Agent 开放了:写几行 TypeScript 就能调 Cursor 干活 AI 技术日报 - 2026-05-01 AI 写代码每次结果都不一样?Archon 用 YAML 工作流把 AI 编程变成流水线 AI 写代码比你快了,但你还是得学编程——只不过学法得换 腾讯的龙虾特工队:4 个 AI Agent 同日更新,全家桶正式成型 Agno 不做更聪明的 Agent,它要把所有 Agent 框架包进同一个操作系统 Hermes Agent 终于有了像样的 Web 界面,而且还支持远程访问 Datawhale 出了一套 29 学科知识地图,把 AI 的底牌全掀了 Hermes Agent 在聊天框里就能用的 20 种高级功能 一份 AGENTS.md 能顶一次模型升级?Augment Code 用数据说了算 NVIDIA 开源了一个「AI 沙箱」,20K Star,让 Agent 跑代码不再裸奔 60ms 冷启动、5MB 内存:腾讯开源的这个沙箱让 Docker 安全隔离像笑话 AI 技术日报 - 2026-04-30 AI 技术日报 - 2026-04-29 AI 技术日报 - 2026-04-28 Goose:Linux 基金会亲儿子,能撼动 Claude Code 和 OpenCode 吗? AI 技术日报 - 2026-04-27 AI 技术日报 - 2026-04-26 Google 把价值20美元/月的东西免费了,102K人已经抢到了 OpenClaw 和 Claude Code 网络搜索配置指南 AI 技术日报 - 2026-04-25 Anthropic 为什么遥遥领先:从 Cat Wu 专访看AI霸主的底层逻辑 Mac 本地跑大模型完全指南:你的苹果电脑就是 AI 工作站 同样 70B 参数,为什么 MoE 只激活 13B 就能打平 Dense? DeepSeek-V4 技术报告里藏着一条线:华为昇腾 NPU 已完成推理验证 DeepSeek-V4 深夜炸场:1M 上下文、384K 输出、双模型,API 定价直接卷到底 MacBook Air 跑大模型实测:Ollama、llama.cpp、LM Studio 谁才是本地推理之王? AI 技术日报 - 2026-04-24
Zero-cost architecture: Build production-grade Web applications with Cloudflare's free services
iTech · 2026-06-21 · via 博客园 - iTech

Zero-cost architecture: Build production-grade Web applications with Cloudflare's free services

In 2026, do I still need to buy a server to make a Web application?

The answer is:Not required in most cases

Cloudflare's free plan is powerful enough to support a mid-scale production-level application without spending a penny. Today I'm here to share a complete and proven architecture solution:

用户请求 → Cloudflare CDN(边缘节点)
         ↓
    Cloudflare Pages(前端静态资源)
         ↓
    Cloudflare Workers(API 服务)
         ↓
    ┌─────────┬─────────┬─────────┐
    │    KV   │   R2    │   D1    │
    │ 缓存/状态 │ 对象存储 │ 数据库   │
    └─────────┴─────────┴─────────┘
         ↓
    Cloudflare Private Network(私有网络)
         ↓
    自有 VPS / 容器(重任务处理)

If this structure is run, if the monthly traffic does not exceed the standard,Cost is 0 yuan

Overview of Cloudflare Free Credit

List the free quota first, and you will know how delicious this thing is:

service free quota what can be done
Workers 100,000 requests/day, CPU time 10ms/request API services are completely sufficient
Pages Unlimited bandwidth, unlimited requests Front-end static hosting
R2 storage 10GB storage, 1 million reads/month, 100,000 writes/month Picture and file storage
KV 1GB storage, 100,000 reads/day, 1000 writes/day caching, session, small state
D1 5GB storage, 5 million rows of reads/month, 100,000 writes/month SQLite relational database
Workers AI 10000 Neurons/day Run AI reasoning
Queue 1 million operations/month asynchronous task queue
Cron Triggers Triggers every hour scheduled task

For an early product, the monthly activity is less than tens of thousands, which is completely within the free quota. Even if it exceeds, Cloudflare's charges are very cheap-Workers is only US$0.3 per million requests, which is much more generous than Vercel and Netlify.

Detailed explanation of hierarchical architecture

Layer 1: Front-end deployment- Cloudflare Pages

This is the simplest layer.

Connect your React/Vue/Svelte/Next.js project to GitHub, Cloudflare Pages will automatically build and deploy it, come with a global CDN, HTTPS will be automatically configured, and preview deployment will be done with one click.

Best practices:

# 安装 Wrangler
npm install -g wrangler

# 本地开发
wrangler pages dev

# 直接部署(甚至不用接 GitHub)
wrangler pages deploy ./.svelte-kit/cloudflare/

Advantages:
- Unlimited bandwidth without Vercel's disgusting traffic restrictions
- 300+ edge nodes around the world, extremely fast
- Automatic HTTPS, automatic compression
- Preview deployment, one independent URL_
- Custom domain names are completely free

Pit reminder:
- Next.js App Router's edge mode support is not as good as Vercel's native_
- SSR can use Workers mode, not Node.js mode_

Layer 2: API layer- Cloudflare Workers_

This is the core of the entire architecture.

Workers 是 Cloudflare 的边缘计算 runtime,用 V8 引擎,冷启动几乎为 0,全球分布,你写的代码自动跑在离用户最近的节点上。

一个最简单的 Worker 示例:

// src/worker.js
export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    // 路由分发
    if (url.pathname === '/api/hello') {
      return new Response(JSON.stringify({
        message: 'Hello from Cloudflare Workers!',
        location: request.cf?.colo  // 告诉你这个请求是哪个边缘节点处理的
      }), {
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // 其他请求走前端静态资源
    return env.ASSETS.fetch(request);
  }
};

wrangler.toml 配置:

name = "my-app"
compatibility_date = "2026-06-01"

# 绑定 Pages 前端
[assets]
directory = "./static"

# 绑定 KV 命名空间
[[kv_namespaces]]
binding = "CACHE"
id = "your-kv-namespace-id"

# 绑定 R2 存储桶
[[r2_buckets]]
binding = "FILES"
bucket_name = "my-app-files"

# 绑定 D1 数据库
[[d1_databases]]
binding = "DB"
database_name = "my-app-db"
database_id = "your-db-id"

Worker 的核心优势:
1. 冷启动为 0:不像 AWS Lambda 有冷启动,Worker 永远是热的
2. 全球分布式:代码自动跑在离用户最近的节点
3. I / O does not block the CPU: Waiting for a response does not take up CPU time
4. Rich binding: Services such as KV, R2, D1, and Queue are directly accessed using env without API Key

Layer 3: Data Layer- KV / R2 / D1

These three layers have their own uses, so do not mix them together.

KV: Cache and Lightweight Status

KV is a globally distributed key-value store, which is most suitable for scenarios where reading more and writing less.

Suitable for:
- Page caching, API response caching
- User sessions, JWT blacklist
- Configuration information, Feature Flag
- Counter, small state

Usage example:

// 缓存 API 响应
const cacheKey = `posts:${page}`;
let posts = await env.CACHE.get(cacheKey, { type: 'json' });

if (!posts) {
  // 缓存没命中,查数据库
  posts = await getPostsFromDB(page);
  // 写入缓存,TTL 1 分钟
  await env.CACHE.put(cacheKey, JSON.stringify(posts), {
    expirationTtl: 60
  });
}

Note: The writing of KV is ultimately consistent, and there may be a 1-2 second delay after writing to read. Do not use it to store data that requires strong consistency.

R2: Object storage

R2 is flare's S3-compatible object store,Zero export flow charge--This is its biggest advantage. The most expensive thing about AWS S3 is not storage, but traffic charges. R2 directly cuts this fee to 0.

Suitable for:
- Storage of pictures, videos, and attachments
- Static resource backup
- log storage
- Any large document

Usage example:

// 上传文件
const formData = await request.formData();
const file = formData.get('file');
const key = `uploads/${crypto.randomUUID()}-${file.name}`;

await env.FILES.put(key, file.stream(), {
  httpMetadata: { contentType: file.type }
});

// 返回公开 URL(R2 可以自定义域名)
return new Response(JSON.stringify({
  url: `https://files.yourdomain.com/${key}`
}));

// 下载/访问文件
const object = await env.FILES.get(key);
if (!object) return new Response('Not found', { status: 404 });
return new Response(object.body, {
  headers: { 'Content-Type': object.httpMetadata.contentType }
});

R2 's trump card: Zero export fees. If you save 10GB of pictures, even if you download 100TB a month, the traffic fee will still be 0. This is something that AWS/Alibaba Cloud dares not imagine.

D1: Relational database

D1 is a distributed relational database built by Cloudflare based on SQLite. It natively supports SQL and is suitable for most application scenarios.

Write SQL directly in Worker:

// 创建用户
const { success } = await env.DB.prepare(`
  INSERT INTO users (id, email, name, created_at)
  VALUES (?, ?, ?, ?)
`)
.bind(crypto.randomUUID(), email, name, Date.now())
.run();

// 查询
const user = await env.DB.prepare(`
  SELECT * FROM users WHERE email = ?
`)
.bind(email)
.first();

// 分页查询
const { results } = await env.DB.prepare(`
  SELECT * FROM posts ORDER BY created_at DESC LIMIT ? OFFSET ?
`)
.bind(limit, offset)
.all();

Database migration:

-- migrations/0001_init.sql
CREATE TABLE users (
  id TEXT PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  name TEXT,
  created_at INTEGER NOT NULL
);

CREATE INDEX idx_users_email ON users(email);
# 执行迁移
wrangler d1 execute my-app-db --file ./migrations/0001_init.sql

# 本地开发用本地数据库
wrangler dev --local

What is D1 suitable for:
- User data, business data
- Transaction processing (ACID supports)
- Medium-scale query (no problem with million-level data)

What is D1 not suitable for:
- Complex JOIN, complex analytical query
- Tens of thousands of writes per second (the free limit is enough, performance needs to be tested)
- Scenarios that require advanced PostgreSQL features

What if D1 is not enough? Cloudflare now supports direct connections Neon/Supabase 的 PostgreSQL, and use the Private Cloud instead of the public network, with extremely low latency.

Layer 4: Heavy task processing-Own VPS/containers

Workers is not everything. It has a CPU time limit (10ms for the free version, 50ms for the paid version) and is not suitable for heavy tasks.

Scenarios that are not suitable for putting workers:
- Picture/Media Processing Service
- PDF generating
- Large data calculation
- WebSocket long connections (Although Workers supports Durable Objects, it is still convenient to build complex scenarios)
- Long-running crawler
- Services that require local file systems

Solution: Put heavy tasks on your own VPS, and workers access the backend through Cloudflare Tunnel (Private Cloud).

用户 → Cloudflare → Worker → 私有网络 → 你的 VPS(公网不可见)

The configuration method is very simple:

1. Install cloudflanged on your VPS:

# 安装
curl -L --output cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
dpkg -i cloudflared.deb

# 认证
cloudflared tunnel login

# 创建隧道
cloudflared tunnel create my-backend

2. Configure tunnel:

# ~/.cloudflared/config.yml
tunnel: your-tunnel-id
credentials-file: /root/.cloudflared/your-tunnel-id.json

ingress:
  # 后端 API 服务跑在本地 8080
  - hostname: api-internal.yourdomain.com
    service: http://localhost:8080
  - 其他服务...
  - service: http_status:404

3. Access the backend in Worker:

// Worker 里直接通过私有域名访问,走 Cloudflare 内部网络
async function processHeavyTask(taskData) {
  // 这个请求走 Cloudflare 私有网络,不经过公网,延迟极低
  const response = await fetch('https://api-internal.yourdomain.com/process', {
    method: 'POST',
    body: JSON.stringify(taskData),
    headers: { 'Content-Type': 'application/json' }
  });
  return response.json();
}

The beauty of this architecture is:
1. Your backend VPS does not require public IP, does not require an open port, and is completely hidden behind Cloudflare
2. There is no need to configure a firewall, Cloudflare can block all DDoS attacks_
3. Workers go to the backend and use Cloudflare Private Cloud, which has lower latency than the public network
4. If the Worker is hung on the back end, it can still be downgraded. The user experience is good.

What about asynchronous tasks? Use Cloudflare Queue!

If heavy tasks do not require synchronous return, use Cloudflare Queue to make asynchronous queues:

// Producer (Worker):发送任务到队列
async function enqueueTask(taskData) {
  await env.QUEUE.send(taskData, {
    contentType: 'json'
  });
  return { status: 'queued' };
}

// Consumer (Worker):处理队列任务
export default {
  async queue(batch, env) {
    for (const message of batch.messages) {
      const task = message.body;
      // 调用后端处理
      await processHeavyTask(task);
      message.ack();
    }
  }
};

The free limit is 1 million times/month, which is enough.

Complete end-to-end process example

Take a photo sharing application as an example:

1. 用户上传图片
   
2. Worker 接收请求把图片原片存到 R2
   
3. 发送消息到 Queue"有新图片需要处理"
   
4. 给用户返回"上传成功"用户不需要等处理完成
   
5. Queue Consumer 收到消息
   
6. 消费者通过私有网络调用 VPS 上的图片处理服务
   
7. VPS 生成缩略图压缩加水印存回 R2
   
8. 更新 D1 数据库把图片状态改为"已处理"
   
9. KV 缓存失效下次访问时拿到新的缩略图

The entire process:
- 前端:Cloudflare Pages
- API: Workers
- Queue: Queue
- Storage: R2
- Database: D1
- Cache: KV
- Heavy tasks: Own VPS, access through Tunnel

User perception: Uploading returns in seconds, processing asynchronously in the background, and the experience is smooth.
Cost: If the traffic is not large, 0 yuan.

cost comparison

To make a calculation, this architecture vs. the traditional Cloud Virtual Machine architecture:

Components Cloudflare solution costs Cost of traditional cloud solutions (Alibaba Cloud/AWS)
Front-end hosting $0 CDN + OSS ≈ $5-20/月
API service $0 (100,000 requests/day) ECS + SLB ≈ $20-50/month
object storage $0 (within 10GB, zero traffic charge) OSS + CDN traffic ≈ $10-100+/month (expensive traffic)
database $0 (within 5GB) RDS ≈ $30-100/月
KV/Cache $0 Redis ≈ $20-50/month
Heavy task VPS One of the cheapest lightweight servers ≈ $3-5/month ibid.
total $3-5/month $88-320+/month

This is not counting operation and maintenance costs-you almost don't need operation and maintenance for Cloudflare architecture. You don't need backup for databases, servers don't need capacity expansion, and CDN don't need configuration.

Guide to Pit Points and Avoidance

Cloudflare free meals are delicious, but there are some pitfalls you need to know:

1. Workers CPU time limit

The free version only has 10ms of CPU time per request, and you will be killed if you exceed it.Note that CPU time is not waiting timeI/O waiting does not count. So if you have a lot of parallel fetches, no problem, because waiting does not take up CPU.

Solve:
- Be asynchronous if you can, don't synchronize, etc.
- CPU-intensive tasks are thrown to backend VPS
- If it is really impossible to upgrade the paid version ($5/month), the CPU time will increase to 50ms

2. Performance of D1

D1 is fast for simple CRUD, but has average performance for complex queries. Don't use D1 as a data warehouse.

Solve:
- Common query plus cache (KV)
- Complex statistical queries are calculated regularly and stored in KV
- If you really need complex queries, use Neon PostgreSQL (you can also connect to Cloudflare Private Cloud)

3. KV consistency

KV is ultimately consistent, and reading immediately after writing may not read the old value.

Solve:
- Don't save anything that requires strong consistency (such as user balances)
- Leave a copy in memory after writing, or add a short delay when reading
- Use D1 for strong consistent needs

4. R2 does not have a native directory list

R2 is an object store, no native"List all files in the directory"Function, list operation is based on prefix.

Solve:
- The file index is stored in D1
- Don't use lists for production logic

5. cold start problem

Workers itself does not have a cold start, but the services you bind to (D1, R2) will request a little slower (a few hundred milliseconds) for the first time after a long period of time.

Solve:
- Use Cron Trigger to beat your heartbeat every hour to keep you alive (free version supported)

# wrangler.toml 加个定时任务保活
[triggers]
crons = ["0 * * * *"]
// Worker 里处理定时任务
async function scheduled(event, env) {
  // 简单访问一下各个服务,保持热状态
  await env.CACHE.get('health-check');
  await env.DB.prepare('SELECT 1').run();
}

When should I pay for upgrades?

The free amount is enough for you to use the product for tens of thousands of months. When should you spend money?

  1. Workers requests more than 100,000 per day - Upgrade Workers Paid ($5/month) to 10 million requests/month, CPU time 50ms
  2. D1 Storage exceeds 5GB - Very cheap, 1GB is only $0.75/month
  3. R2 storage exceeds 10GB - 1GB $0.015/month is almost equal to free
  4. Need for greater reliability and performance - Upgrade Paid version with SLA

At full cost, for a product that earns 100,000 yuan a month, the cost of a full set of Cloudflare is only $10-20, which is cheaper than buying a separate server.

written in the end

Cloudflare is doing something terrible: it is turning the entire infrastructure layer of the Internet into a public utility, just like water and electricity-you pay for whatever you use, and small users use it for free.

This architecture is not a toy, it can really be produced. Many products with hundreds of thousands or even millions of users are now running on this free/low-cost architecture.

One of the greatest freedoms of technical people is that they can turn ideas into products at extremely low cost.

In the past, if you wanted to make a product, you had to buy a server, configure a database, build a CDN, and engage in Load Balancer. After a long time, you hadn't even started writing business code. Now, you just need to focus on writing code, and the rest of Cloudflare will help you handle it, and the first tens of thousands of users are free.

This is the best era. Go do what you want to do.


reference resource

  1. Cloudflare Workers official documents - _ _ JHSNS _ URL _ 0 _ _
    The most authoritative reference, the API documentation is very detailed

  2. Cloudflare D1 文档 - _ _ JHSNS _ URL _ 0 _ _
    Complete guide to D1 databases, including SQL references and best practices

  3. Cloudflare Tunnel Documentation - _ _ JHSNS _ URL _ 0 _ _
    Detailed Configuration Guide for the Backend of Private Cloud Connection

  4. Awesome Cloudflare Workers - _ _ JHSNS _ URL _ 0 _ _
    Selected resource list on GitHub, including a large number of open source projects and templates


author: itech001
source: Public Account: AI Artificial Intelligence Era
website: _ _ JHSNS _ URL _ 0 _ _
Share the most cutting-edge AI news and technical research every day.

This article was first published in the era of AI artificial intelligence. Please indicate the source for reprinting.