










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。
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.
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_
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
These three layers have their own uses, so do not mix them together.
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 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 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.
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(公网不可见)
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.
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.
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.
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.
Cloudflare free meals are delicious, but there are some pitfalls you need to know:
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
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)
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
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
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();
}
The free amount is enough for you to use the product for tens of thousands of months. When should you spend money?
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.
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.
Cloudflare Workers official documents - _ _ JHSNS _ URL _ 0 _ _
The most authoritative reference, the API documentation is very detailed
Cloudflare D1 文档 - _ _ JHSNS _ URL _ 0 _ _
Complete guide to D1 databases, including SQL references and best practices
Cloudflare Tunnel Documentation - _ _ JHSNS _ URL _ 0 _ _
Detailed Configuration Guide for the Backend of Private Cloud Connection
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.
This content is automatically aggregated by InertiaRSS (RSS Reader) for reading reference only. Original from — Copyright belongs to the original author.