Serverless Computing, Reimagined
Cloudflare Workers is a serverless execution environment that runs your code on Cloudflare's global network. Unlike traditional serverless platforms, Workers execute in V8 isolates with near-zero cold starts, making them perfect for latency-sensitive applications like ProposalForge.
What Makes Workers Different?
β‘ Zero Cold Starts
Workers start in less than 1ms using V8 isolates, not containers. No waiting for infrastructure to spin up.
π Edge Execution
Code runs in 300+ cities worldwide, within milliseconds of your users, automatically.
π° Unbeatable Pricing
100,000 requests per day free. After that, just $0.50 per million requests.
π§ Full JavaScript/TypeScript
Write modern JavaScript or TypeScript with npm packages. Use familiar web APIs and frameworks.
π Integrated Ecosystem
Direct access to D1 databases, R2 storage, KV, Durable Objects, and moreβno network hops.
π Unlimited Scaling
Automatically scales from 0 to millions of requests per second without configuration.
How ProposalForge Uses Workers
ProposalForge leverages Cloudflare Workers through Pages Functions to handle server-side operations:
π€ PDF Upload API
Workers receive PDFs from the browser and upload them to R2 storage with proper organization.
πΎ Database Operations
All D1 database queries run through Workers for secure, server-side data access.
π API Key Management
Sensitive credentials stored in Worker environment variables, never exposed to clients.
π― Request Routing
Workers handle API routes (/api/*) while serving static assets from Pages.
Example Worker: PDF Upload Endpoint
// functions/api/upload-pdf.ts
export async function onRequestPost({ request, env }) {
try {
// Parse multipart form data
const formData = await request.formData();
const file = formData.get('file');
if (!file || file.type !== 'application/pdf') {
return Response.json(
{ error: 'Invalid file type' },
{ status: 400 }
);
}
// Generate organized storage path
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const filename = file.name.replace(/[^a-zA-Z0-9.-]/g, '_');
const key = `proposals/${year}/${month}/${filename}`;
// Upload to R2 with metadata
await env.R2_BUCKET.put(key, file.stream(), {
httpMetadata: {
contentType: 'application/pdf',
cacheControl: 'public, max-age=31536000'
},
customMetadata: {
uploadedAt: date.toISOString(),
fileSize: String(file.size),
originalName: file.name
}
});
// Save to D1 database
await env.DB.prepare(`
INSERT INTO pdf_generations
(filename, file_size, cloud_url, generated_at)
VALUES (?, ?, ?, ?)
`).bind(
filename,
file.size,
`https://cdn.example.com/${key}`,
date.toISOString()
).run();
// Return success with public URL
return Response.json({
success: true,
url: `https://cdn.example.com/${key}`,
size: file.size
});
} catch (error) {
console.error('Upload failed:', error);
return Response.json(
{ error: 'Upload failed', details: error.message },
{ status: 500 }
);
}
}
Workers vs Traditional Serverless
| Feature |
Cloudflare Workers |
AWS Lambda |
| Cold Start |
< 1ms (V8 isolates) |
100-1000ms (containers) |
| Execution Time |
50ms CPU time (free tier) |
15 minutes max |
| Memory |
128MB default |
128MB - 10GB configurable |
| Global Deployment |
Automatic (300+ locations) |
Manual (regional) |
| Free Tier |
100,000 requests/day |
1 million requests/month |
| Pricing |
$0.50 per million |
$0.20 per million (+ duration) |
| Network Latency |
< 10ms (edge execution) |
50-200ms (regional) |
V8 Isolates: The Secret Sauce
Workers use V8 isolates instead of containers or VMs:
- β‘ Instant Startup: Isolates initialize in microseconds, not seconds
- πΎ Memory Efficient: Thousands of isolates can run on a single machine
- π Secure: Each isolate is completely isolated from others
- π Native Performance: V8 compiles JavaScript to native machine code
- β»οΈ No Warm-up: First request is as fast as the millionth
Pages Functions vs Workers
ProposalForge uses Pages Functions, which are Workers specifically designed for Pages deployments:
π File-Based Routing
Functions in /functions/api/*.ts automatically become API routes at /api/*
π Git Integration
Functions deploy automatically with your Pages siteβno separate Worker deployment.
π― TypeScript Support
Write typed Functions with full IDE support and compile-time checking.
π Environment Bindings
Automatically access D1, R2, KV, and environment variables in context.env
Worker Bindings in ProposalForge
// wrangler.toml - Worker configuration
name = "proposalforge"
[env.production]
# D1 Database binding
[[env.production.d1_databases]]
binding = "DB"
database_name = "proposal-db"
database_id = "xxxx-xxxx-xxxx-xxxx"
# R2 Storage binding
[[env.production.r2_buckets]]
binding = "R2_BUCKET"
bucket_name = "proposal-pdfs"
# Environment variables
[env.production.vars]
ENVIRONMENT = "production"
Performance Optimizations
π― Edge Caching
Workers can set Cache-Control headers to cache responses at the edge for instant delivery.
π¦ Bundle Optimization
Workers are bundled with esbuild, removing unused code for minimal payload size.
π Streaming Responses
Stream large responses to clients without buffering the entire response in memory.
β‘ Parallel Execution
Use Promise.all() to run multiple operations concurrently for faster response times.
Error Handling & Monitoring
// Comprehensive error handling
export async function onRequest({ request, env }) {
try {
// Worker logic here
const result = await processRequest(request, env);
return Response.json({ success: true, data: result });
} catch (error) {
// Log error to console (appears in dashboard)
console.error('Worker error:', {
message: error.message,
stack: error.stack,
url: request.url,
method: request.method
});
// Return user-friendly error
return Response.json(
{
success: false,
error: 'Internal server error',
requestId: crypto.randomUUID()
},
{ status: 500 }
);
}
}
Security Best Practices
- π Environment Variables: Store API keys in Worker secrets, never in code
- π‘οΈ Input Validation: Validate all user input before processing
- π¨ Rate Limiting: Implement request throttling to prevent abuse
- π CORS Headers: Configure proper CORS to prevent unauthorized access
- π Request Logging: Log suspicious activity for security monitoring
Cost Structure Free Tier
ProposalForge runs entirely on the free tier:
- π Free: 100,000 requests per day
- π Free: 10ms CPU time per request
- π Paid: $5/month for 10 million requests
- π Paid: $0.02 per additional million requests
Developer Experience
π οΈ Wrangler CLI
Local development, testing, and deployment with a single command-line tool.
π Live Logs
Stream real-time logs from production Workers using wrangler tail.
π Analytics Dashboard
Monitor requests, errors, CPU usage, and performance metrics in real-time.
π§ͺ Local Testing
Test Workers locally with Miniflare before deploying to production.