
Why I almost paid AWS 8x more for the same bot I ran for free
a 3 month journey of building an automation on cloudflare having to deal with constant failures to finally migrating it to aws
The Problem
I started by building a Telegram bot that serves Kenyan stock market intelligence: daily reports, PDF filing analysis, AI-powered Q&A, and a blog publishing pipeline. It ran on Cloudflare Workers with D1, R2, and Queues. It worked. Then I hit the wall: a 50-subrequest-per-invocation limit, 128MB memory ceiling, and a database that couldn't do JOINs across tables without hitting runtime limits. I needed to migrate to AWS.
This article documents the actual migration. Not a toy example, but a production system with 14 database tables, 3 cron schedules, a queue consumer, and 25+ HTTP endpoints.
What the System Actually Does
Before mapping services, here's what we're working with:
Component | What It Does |
|---|---|
Telegram Bot | Webhook receiver, 10+ commands, rate limiting, 3900-char message chunking |
Daily Report | Scrapes 8 websites, calls AI for narrative, sends to Telegram, archives in DB |
PDF Pipeline | Crawls 10 broker sites hourly, queues PDFs, extracts text, generates AI summaries, stores in object storage |
Blog Engine | Runs unattended on a cron schedule: scrapes source material, refines it into 3 categories of posts (daily brief, education, deep dive) via AI, commits to GitHub, and triggers a Vercel deploy hook. End to end, no human in the loop. |
Recommendation Engine | Scores equities from event signals, tracks entry/exit prices, calculates returns |
AI Integration | Dual-provider failover (Vercel AI Gateway to Mistral), used in 6 different places |
Service Mapping: Cloudflare to AWS
Here's what I actually mapped, not what a whitepaper tells you to use.
Cloudflare | AWS Service | Why This One |
|---|---|---|
Workers | Lambda | 15-min timeout covers the 4-min daily report. 10GB memory is more than enough. |
D1 (SQLite) | RDS PostgreSQL (db.t4g.micro); Aurora Serverless v2 only if you outgrow it | D1 can't do JOINs well; Postgres solves that either way. RDS gives you the same JOIN/CTE support as Aurora at a fraction of the cost. See the cost section below for why this matters when you're coming from a $0 bill. |
R2 (Object Storage) | S3 | Direct replacement. R2 is S3-compatible anyway. |
Queues | SQS + Lambda | SQS for the queue, Lambda as consumer. More control over batch size and concurrency. |
Workers Triggers (Cron) | EventBridge Scheduler | Cron expressions, timezone support, retry policies: all built in. |
caches.default (Edge Cache) | DynamoDB DAX or ElastiCache Redis | In-memory cache layer for hot paths (/ask command, web search results). |
Workers Secrets | Secrets Manager or SSM Parameter Store | Secrets Manager for the API keys, SSM for config vars. |
Workers KV (not used but planned) | DynamoDB | For the two-tier cache we had with in-memory + edge. |
Architecture Diagram

The system splits into three flows: the live request path (Telegram commands and admin calls), the hourly PDF ingestion pipeline, and the daily blog agent pipeline. See the interactive diagrams shared alongside this article for the full service-level breakdown of each.
The Hard Parts (What Nobody Tells You)
1. The Subrequest Limit Doesn't Exist, But Cold Starts Do
Cloudflare Workers has a 50-subrequest limit per invocation. I spent weeks working around it: splitting the daily report from blog publishing, staggering PDF rehydration, limiting concurrent fetches.
On Lambda, that constraint disappears. But cold starts become real. The daily report function calls 8 external websites sequentially with 20-second timeouts. A cold start plus network latency can push you toward the 15-minute Lambda timeout.
What I did: I added provisioned concurrency (2 instances) for the 4 AM daily report. Cost me about $12/month, but the report now runs in 3-4 minutes instead of 8-12.
2. D1 to Postgres: The Schema Migration
D1 is SQLite. I moved to standard PostgreSQL (via RDS
db.t4g.micro ; see the cost section for why RDS instead of Aurora Serverless v2). Everything below applies identically whether you run it on RDS or Aurora; the engine and SQL are the same, only the billing model differs. The differences from SQLite matter regardless of which Postgres you pick:-- D1 (SQLite): what workedCREATE TABLE IF NOT EXISTS pdfs ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT UNIQUE, company_symbol TEXT, summary TEXT);
-- Aurora (PostgreSQL): what I actually neededCREATE TABLE pdfs ( id SERIAL PRIMARY KEY, url TEXT UNIQUE NOT NULL, company_symbol VARCHAR(10), summary TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
-- The recommendation engine query that CRASHED on D1-- but runs in 12ms on Aurora:WITH company_scores AS ( SELECT company_symbol, COUNT(*) as event_count, AVG(confidence) as avg_confidence, SUM(CASE WHEN event_type LIKE 'earnings_positive%' THEN 1 ELSE 0 END) as positive_signals FROM market_events WHERE event_date >= CURRENT_DATE - INTERVAL '90 days' GROUP BY company_symbol)SELECT * FROM company_scoresWHERE event_count >= 3ORDER BY positive_signals DESC, avg_confidence DESC;
D1 chokes on CTEs with aggregations over 50k rows. Postgres, on RDS or Aurora alike, handles it in milliseconds.
3. Queue Processing: SQS Batches vs Cloudflare Queues
Cloudflare Queues gives you a batch of messages and you process them synchronously. Simple. SQS + Lambda is more powerful but more complex:
// Cloudflare (simple)async queue(batch: MessageBatch<PdfQueueMessage>, env: Env) { for (const message of batch.messages) { await processPdfMessage(message.body, env); message.ack(); }}
// AWS (more control, more config)// Lambda triggered by SQS, configured with:// BatchSize: 5// MaximumBatchingWindowInSeconds: 30// MaxConcurrency: 1 (same as CF Workers)// Retry attempts: 3// Dead letter queue: another SQS queue
The advantage: AWS gives you a dead letter queue. Cloudflare Queues doesn't. When a PDF URL is permanently broken (404), Cloudflare retries indefinitely. AWS routes it to the DLQ after 3 attempts.
4. Cron Scheduling: EventBridge Scheduler > Workers Triggers
Cloudflare Workers Triggers use cron expressions but have quirks: timezone handling is UTC-only, retry policies are limited, and you can't easily pause/resume a schedule.
EventBridge Scheduler gives you:
{ "ScheduleExpression": "cron(0 4 * * ? *)", "ScheduleExpressionTimezone": "Africa/Nairobi", "FlexibleTimeWindow": { "Mode": "OFF" }, "Target": { "Arn": "arn:aws:lambda:af-south-1:123456789:function:daily-report", "RoleArn": "arn:aws:iam::123456789:role/eventbridge-lambda-role" }, "State": "ENABLED"}
The timezone support alone is worth the switch. My daily report runs at 4 AM EAT (not UTC), and I can pause it from the console during maintenance.
5. The AI Provider Failover
My system tries Vercel AI Gateway first, then falls back to Mistral. On AWS, I replaced this with Amazon Bedrock agent core:
// Before (Cloudflare)async function callAi(env: Env, prompt: string, text?: string) { if (env.AI_GATEWAY_API_KEY) { return await callVercelGateway(prompt, text, env.AI_GATEWAY_API_KEY, ...); } if (env.MISTRAL_API_KEY) { return await callMistral(prompt, text, env.MISTRAL_API_KEY, ...); } throw new Error("No AI API keys configured");}
// After (AWS)async function callAi(prompt: string, text?: string) { const bedrock = new BedrockRuntimeClient({ region: "af-south-1" }); const command = new InvokeModelCommand({ // af-south-1 doesn't host models directly. // Use a cross-region inference profile (global or geo) to reach // the Claude 4.x family from Cape Town. Check the current profile // ID in the Bedrock console before deploying; these IDs are // updated as new model versions ship. modelId: "global.anthropic.claude-haiku-4-5-20251001-v1:0", body: JSON.stringify({ messages: [{ role: "user", content: `${prompt}\n\n${text || ""}` }], max_tokens: 2000 }) }); const response = await bedrock.send(command); return JSON.parse(new TextDecoder().decode(response.body)).content[0].text;}
Bedrock agent core removes the API key management entirely. No more dual-provider failover logic: Bedrock handles retries and model availability internally. One gotcha: the original Claude 3 Haiku model ID from 2024 is long superseded.
us-east-1 now reaches the Claude 4.5 family (Haiku 4.5, Sonnet 4.5, Opus 4.5) through global cross-Region inference profiles rather than in-Region hosting, so budget a small IAM/quota step to enable that profile before your first invocation.
Cost Comparison (Rough Numbers)
This system ran entirely inside Cloudflare's free tier. Workers, D1, R2, and Queues all comfortably under free-tier limits at this traffic volume. The Cloudflare bill was $0. Any AWS migration that lands meaningfully above that needs a real justification, not just "AWS is more capable."
The mistake in an early pass of this cost model was defaulting to Aurora Serverless v2, which has a 0.5 ACU minimum that costs about $44/month in compute alone, even completely idle. That single decision was responsible for almost the entire AWS bill.
Swapping it for RDS PostgreSQL on a
db.t4g.micro instance keeps the same Postgres engine (same JOINs, same CTEs, same schema from the section above) without the serverless idle tax, and it's free-tier eligible for a new AWS account's first 12 months.Service | Cloudflare (Monthly) | AWS: Year 1 (Free Tier) | AWS: Ongoing (after Free Tier) |
|---|---|---|---|
Compute | $0 (Workers free tier) | $0 (Lambda: 1M requests + 400,000 GB-s free/month) | $0 to $5 (~500k invocations/month is still mostly inside free tier) |
Database | $0 (D1 free tier) | $0 (RDS db.t4g.micro, 750 hrs/month free for 12 months) | ~$13 to $15 (db.t4g.micro on-demand) |
Object Storage | $0 (R2 free tier) | $0 (S3: 5GB free) | $1 to $3 (~5GB of PDFs) |
Queue | $0 (Queues free tier) | $0 (SQS: 1M requests free) | $1 to $2 (<1M requests) |
Cron | $0 (included) | $0 (EventBridge free tier) | $0 |
API Gateway | $0 (included) | $0 (1M REST API calls free for 12 months) | $3 to $5 |
Secrets | $0 (wrangler secret) | $0 (SSM Parameter Store, standard tier is free) | $0 (stay on SSM standard; skip Secrets Manager's $0.40/secret/month unless you need rotation) |
Total | $0 | ~$0 | ~$15 to $25 |
So: realistically, this migration doesn't pay for itself in year one. AWS's free tier covers almost the whole stack, landing close to $0. After the free tier lapses, expect roughly $15 to $25/month, not the $60 to $80 an Aurora-based setup would cost.
That's the honest number to weigh against what you're actually migrating for: a real relational database with working JOINs, a dead letter queue, timezone-aware scheduling, and no subrequest ceiling. If those aren't blocking you today, it's fair to stay on Cloudflare. The free tier is genuinely free, and $15 to $25/month isn't nothing when the alternative is $0.
What I'd Do Differently
- Split the Lambda earlier. The daily report function does too much: 8 web scrapes, AI call, DB writes, Telegram send. I should have split it into a Step Functions workflow: scrape, process, generate, send.
- Use DynamoDB for the cache layer. The in-memory Map + edge cache pattern works on Cloudflare because Workers run at the edge. On Lambda, there's no shared memory. DynamoDB with DAX gives me the same speed without the complexity.
- Start with PostgreSQL, not MySQL, and start on RDS, not Aurora Serverless v2. The JSONB type in Postgres handles the unstructured market event data better than MySQL's JSON type, so Postgres was the right call. But I initially reached for Aurora Serverless v2 out of habit, and its 0.5 ACU minimum (~$44/month, even fully idle) turned out to be the single biggest line item in the whole migration, for a system that used to run at $0. RDS
db.t4g.microgives the same engine and same JOIN/CTE support for a fraction of the cost, and it's free-tier eligible in year one.
- Use Lambda Destinations instead of manual error handling. SQS to Lambda to DLQ is simpler than the try/catch/retry logic I ported from Cloudflare.
- Price things out before committing to "serverless" defaults. Serverless billing sounds cheap by name, but Aurora Serverless v2's idle floor is a fixed cost regardless of traffic. If you're migrating off a genuinely free platform, the provisioned/always-on option is often the cheaper one at low-to-moderate scale. The "serverless" label doesn't automatically mean lower cost.
Migration Checklist
If you're doing a similar Cloudflare to AWS migration:
- [ ] Map Workers to Lambda (+ API Gateway for HTTP endpoints)
- [ ] Map D1 to RDS PostgreSQL
db.t4g.micro(or DynamoDB for simple key-value; only reach for Aurora Serverless v2 if you actually need its autoscaling, and know its ~$44/month idle floor going in)
- [ ] Map R2 to S3
- [ ] Map Queues to SQS + Lambda consumer + DLQ
- [ ] Map Workers Triggers to EventBridge Scheduler
- [ ] Move secrets to SSM Parameter Store (or Secrets Manager if you need rotation)
- [ ] Set up VPC (Lambda needs it for RDS/Aurora)
- [ ] Add provisioned concurrency for latency-sensitive paths
- [ ] Set up CloudWatch alarms for Lambda errors and duration
- [ ] Test cold start times and adjust memory/timeout
- [ ] Migrate schema (SQLite to PostgreSQL has gotchas)
- [ ] Update environment variables to SSM Parameter Store
- [ ] Set up CI/CD (GitHub Actions to Lambda deploy)
- [ ] Confirm which Bedrock model IDs and inference profiles are current for your region before hardcoding one
Conclusion
Cloudflare Workers is excellent for edge compute and simple serverless apps. Worth saying plainly: this system ran on Cloudflare's free tier at $0/month, so "AWS is more capable" only matters if you actually need that capability.
When you need a real database with working JOINs, a dead letter queue, and production-grade queue processing, AWS gives you the tooling to do it right, and if you avoid Aurora Serverless v2's idle floor and stick to RDS, it can land close to $0 in year one on AWS's own free tier, settling around $15 to $25/month afterward.
The migration cost me about 2 weekends of work. Whether the extra $15 to $25/month is worth it depends entirely on whether D1's JOIN limitations were actually blocking you.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article