
Building Three Full-Stack Apps with AWS Blocks Zero AWS Cost
How I built a Bookmark Manager, Live Polls, and an AI Help Desk using Infrastructure from Code - all running locally without spending a single cent on cloud resources.
Introduction
What if you could build production-grade full-stack applications with authentication, real-time WebSockets, AI agents, file storage, and observability all without an AWS account, without cloud credentials, and at absolutely zero cost?
That's exactly what I did during the AWS Blocks Skill Sprint. I built three progressively complex applications using AWS Blocks an Infrastructure from Code framework that provides local mock implementations of every AWS service it maps to.
This article walks through all three challenges: the problem each one solves, the architecture, how I built it, and what I learned.
What is AWS Blocks?
AWS Blocks is a TypeScript-first framework where you declare your infrastructure as code constructs (called "Building Blocks") and the same code runs:
- Locally with zero-cost mock implementations (JSON on disk, in-memory queues, local WebSocket servers)
- On AWS mapping to real services (DynamoDB, Cognito, S3, Bedrock, API Gateway WebSocket, CloudWatch)
You write your backend once. The framework handles the environment.
import { Scope, ApiNamespace, DistributedTable, AuthBasic } from '@aws-blocks/blocks';
const scope = new Scope('my-app');const auth = new AuthBasic(scope, 'auth');const table = new DistributedTable(scope, 'items', { schema, key });
export const api = new ApiNamespace(scope, 'api', (context) => ({ async createItem(input) { const user = await auth.requireAuth(context); await table.put({ userId: user.userId, ...input }); },}));
Challenge 1: Personal Bookmark Manager
Problem Statement
Users need a private space to save, organize, and retrieve web links. The solution must enforce strict data isolation — User A must never see User B's bookmarks, even if they share the same application instance.
Solution
A CRUD application with:
- Username/password authentication
- User-partitioned bookmark storage with schema validation
- Server-derived identity (the browser never sends a userId)
Architecture Diagram

Code Breakdown
Imports what each Block does:
import { ApiNamespace, Scope, AuthBasic, DistributedTable } from '@aws-blocks/blocks';import { z } from 'zod';
Import | Role |
|---|---|
Scope | Application boundary — all blocks share this identity |
AuthBasic | Username/password auth with JWT sessions |
DistributedTable | Schema-validated DynamoDB-like storage with keys and queries |
ApiNamespace | Type-safe RPC endpoint (auto-generates frontend client) |
z (Zod) | Runtime schema validation for all records |
Block initialization:
const scope = new Scope('bookmark-app');
const auth = new AuthBasic(scope, 'auth', { passwordPolicy: { minLength: 8 },});
export const authApi = auth.createApi(); // Drives the Authenticator UI
const bookmarkSchema = z.object({ userId: z.string(), // Partition key — server-derived bookmarkId: z.string(), // Sort key — server-generated UUID url: z.string().url(), title: z.string().min(1), tag: z.string(), createdAt: z.number(),});
const bookmarks = new DistributedTable(scope, 'bookmarks', { schema: bookmarkSchema, key: { partitionKey: 'userId', sortKey: 'bookmarkId' },});
API every method derives identity server-side:
export const bookmarkApi = new ApiNamespace(scope, 'api', (context) => ({ async createBookmark(input: { url: string; title: string; tag: string }) { const user = await auth.requireAuth(context); // 401 if not signed in const userId = user.username; // Server-derived — never from browser const bookmarkId = crypto.randomUUID(); // Server-generated const createdAt = Date.now(); // Server timestamp
const record = bookmarkSchema.parse({ userId, bookmarkId, ...input, createdAt }); await bookmarks.put(record); return record; },
async listBookmarks() { const user = await auth.requireAuth(context); return await Array.fromAsync( bookmarks.query({ where: { userId: { equals: user.username } } }) ); },
async deleteBookmark(bookmarkId: string) { const user = await auth.requireAuth(context); await bookmarks.delete({ userId: user.username, bookmarkId }); // Ownership enforced by key return { success: true }; },}));
Key Design Decisions
- Server-generated IDs
bookmarkIdandcreatedAtare never accepted from the client
- Partition isolation Querying by
userIdmeans you physically cannot access another user's partition
- Schema validation Zod rejects malformed data before it reaches the table
Challenge 2: Live Polls
Problem Statement
Build a real-time collaborative polling system where multiple users see vote counts update live without refreshing the page. Ensure exactly one vote per user with no race conditions, even under concurrent access.
Solution
A real-time polling app with:
- WebSocket-based live result broadcasting
- One-vote-per-user enforcement via conditional writes
- Optimistic concurrency with revision tracking
- Background job processing for poll summaries
- State recovery after disconnection
Architecture Diagram

Code Breakdown
Imports — adding Realtime and AsyncJob:
import { Scope, ApiNamespace, AuthBasic, DistributedTable, Realtime, AsyncJob,} from '@aws-blocks/blocks';import { z } from 'zod';
Import | Role |
|---|---|
Scope | Application boundary |
AuthBasic | Username/password auth |
DistributedTable | Two tables — Polls and Votes |
Realtime | WebSocket pub/sub for live updates |
AsyncJob | Fire-and-forget background processing |
ApiNamespace | Type-safe RPC endpoint |
Realtime setup — typed namespaces:
const realtime = new Realtime(scope, 'poll-updates', { namespaces: { results: Realtime.namespace( z.object({ pollId: z.string(), question: z.string(), options: z.array(z.string()), votes: z.record(z.string(), z.number()), totalVotes: z.number(), status: z.enum(['open', 'closed']), revision: z.number(), summary: z.string().optional(), }) ), },});
AsyncJob background summary generation:
const summaryJob = new AsyncJob(scope, 'poll-summary', { schema: z.object({ pollId: z.string() }), handler: async (payload) => { const poll = await polls.get({ pollId: payload.pollId }); if (!poll) return;
const winner = poll.options.reduce((best, opt, idx) => { const count = poll.votes[String(idx)] || 0; return count > best.count ? { option: opt, count } : best; }, { option: '', count: -1 });
const summary = `Winner: "${winner.option}" with ${winner.count} votes.`; await polls.put({ ...poll, summary, revision: poll.revision + 1 }); await realtime.publish('results', payload.pollId, { ...poll, summary, revision: poll.revision + 1 }); },});
Vote with one-vote-per-user enforcement:
async vote(input: { pollId: string; optionIndex: number }) { const user = await auth.requireAuth(context);
const poll = await polls.get({ pollId: input.pollId }); if (!poll) throw new Error('Poll not found'); if (poll.status === 'closed') throw new Error('Poll is closed');
// One vote per user — check before write const existingVote = await votes.get({ pollId: input.pollId, userId: user.username }); if (existingVote) throw new Error('You have already voted on this poll');
// Record the vote await votes.put({ pollId: input.pollId, userId: user.username, optionIndex: input.optionIndex, votedAt: Date.now(), });
// Update tally with revision bump (optimistic concurrency) const updatedVotes = { ...poll.votes }; updatedVotes[String(input.optionIndex)] = (updatedVotes[String(input.optionIndex)] || 0) + 1;
const updatedPoll = { ...poll, votes: updatedVotes, totalVotes: poll.totalVotes + 1, revision: poll.revision + 1 }; await polls.put(updatedPoll);
// Publish FULL snapshot — never a delta await realtime.publish('results', poll.pollId, updatedPoll); return { success: true, poll: updatedPoll };}
Key Design Decisions
- Full snapshots, not deltas - Every publish sends the complete state. Simpler clients, guaranteed consistency
- Revision gating - Clients only apply updates where
incoming.revision > local.revision
- State recovery - On WebSocket reconnect, the client calls
getPoll()to fetch canonical state from the database
Challenge 3: AI Help Desk
Problem Statement
Build an intelligent support system where customers get instant AI-powered answers from a knowledge base, with seamless escalation to human agents. Agents need real-time ticket monitoring, document management, and role-protected access. The system must handle rate limiting, structured logging, and operational metrics.
Solution
A multi-role application with:
- AI agent that searches documentation and creates tickets
- Role-based access control (customers vs agents)
- Real-time ticket queue with live updates
- Protected file uploads with validation
- Per-user rate limiting with optimistic concurrency
- Full observability (structured logs + metrics)
Code Breakdown
Imports - the full arsenal:
import { Scope, ApiNamespace, AuthCognito, DistributedTable, DistributedTableErrors, FileBucket, KnowledgeBase, Agent, Realtime, Logger, Metrics, isBlocksError,} from '@aws-blocks/blocks';import { z } from 'zod';
Import | Role |
|---|---|
AuthCognito | Cognito-backed auth with groups (RBAC) |
DistributedTable | Tickets table + rate limit counters |
DistributedTableErrors | Error constants for conditional write failures |
FileBucket | S3-like file storage for document uploads |
KnowledgeBase | Semantic search over markdown documents |
Agent | AI agent with tool calling and conversation persistence |
Realtime | WebSocket pub/sub for live ticket updates |
Logger | Structured JSON logging |
Metrics | CloudWatch EMF metrics emission |
isBlocksError | Type-safe error matching |
AuthCognito with role groups:
const auth = new AuthCognito(scope, 'auth', { passwordPolicy: { minLength: 8, requireDigits: true }, groups: ['agent'], // Role-based access control selfSignUp: true, codeDelivery: async (username, code, purpose) => { logger.info('Auth code delivered', { username, purpose }); },});
AI Agent with tools:
const supportAgent = new Agent(scope, 'support-agent', { model: { deployed: { provider: 'bedrock', modelId: 'us.anthropic.claude-sonnet-4-6' }, local: { provider: 'canned' }, // Zero-cost local mock }, systemPrompt: 'You are a helpful AI support agent...', toolContextSchema: z.object({ userId: z.string() }), tools: (tool) => ({ searchHelpDocs: tool({ description: 'Search help documentation for answers', parameters: z.object({ query: z.string() }), handler: async ({ input }) => { const results = await kb.retrieve(input.query, { maxResults: 3 }); metrics.emit('KnowledgeRetrievalLatency', Date.now() - startTime, { unit: 'Milliseconds' }); return results.map((r) => ({ answer: r.text, source: r.source, score: r.score })); }, }), createTicket: tool({ description: 'Escalate to a human agent by creating a ticket', parameters: z.object({ subject: z.string(), description: z.string() }), handler: async ({ input, context }) => { const userId = (context as { userId: string }).userId; const ticket = { ticketId: crypto.randomUUID(), customerId: userId, ...input, status: 'open', version: 1 }; await tickets.put(ticket); metrics.emit('TicketsCreated', 1, { unit: 'Count' }); await realtime.publish('tickets', 'all', ticket); // Live notification to agents return { ticketId: ticket.ticketId, status: 'open' }; }, }), }),});
Rate limiter with optimistic concurrency:
async function checkRateLimit(userId: string): Promise<boolean> { const windowKey = String(Math.floor(Date.now() / 60_000)); // 1-minute window const maxRetries = 3;
for (let attempt = 0; attempt < maxRetries; attempt++) { const existing = await rateLimits.get({ userId, windowKey });
if (!existing) { try { await rateLimits.put({ userId, windowKey, count: 1, version: 1 }, { ifNotExists: true }); return true; // First request in window } catch (e: unknown) { if (isBlocksError(e, DistributedTableErrors.ConditionalCheckFailed)) continue; throw e; } }
if (existing.count >= 10) return false; // RATE LIMITED
try { await rateLimits.put( { userId, windowKey, count: existing.count + 1, version: existing.version + 1 }, { ifFieldEquals: { version: existing.version } } // Optimistic concurrency ); return true; } catch (e: unknown) { if (isBlocksError(e, DistributedTableErrors.ConditionalCheckFailed)) continue; throw e; } } return false; // Exhausted retries}
Agent-only APIs with role gating:
// Customer endpoint — requireAuth onlyasync chatWithAgent(input: { message: string; conversationId?: string }) { const user = await auth.requireAuth(context); const allowed = await checkRateLimit(user.username); if (!allowed) { metrics.emit('RateLimitRejected', 1, { unit: 'Count' }); throw new Error('Rate limit exceeded.'); } metrics.emit('AgentRequests', 1, { unit: 'Count' }); // ... invoke AI agent}
// Agent-only endpoint — requireRole gates accessasync updateTicketStatus(input: { customerId: string; ticketId: string; status: string }) { await auth.requireRole(context, 'agent'); // 403 if not in 'agent' group const ticket = await tickets.get({ customerId: input.customerId, ticketId: input.ticketId }); const updated = { ...ticket, status: input.status, version: ticket.version + 1 }; await tickets.put(updated, { ifFieldEquals: { version: ticket.version } }); await realtime.publish('tickets', 'all', updated); return updated;}
// Agent-only file upload with validationasync uploadDocument(input: { filename: string; content: string }) { await auth.requireRole(context, 'agent'); if (!validateFilename(input.filename)) throw new Error('Only .md and .txt allowed'); if (!validateFileContent(input.content)) throw new Error('File too large or empty'); await uploads.put(`help-staging/${input.filename}`, input.content); metrics.emit('HelpDocsStaged', 1, { unit: 'Count' });}
Key Design Decisions
- Agent tools reuse services - The
createTickettool calls the same ticket service code, so tickets created by AI go through identical validation and realtime publishing
- Rate limit before AI - The limiter rejects requests before invoking the Agent, preventing expensive model calls
- Full snapshots on Realtime - Agents always get the complete ticket state, enabling reliable state recovery after reconnect
- Never log secrets - Logger explicitly avoids prompts, document content, upload URLs, and credentials
Cost: Absolutely Zero
Resource | Production AWS Service | Local Mock Implementation | Cost |
|---|---|---|---|
Authentication | Amazon Cognito | Local JWT + JSON state | $0 |
Database | Amazon DynamoDB | JSON files in .bb-data/ | $0 |
File Storage | Amazon S3 | Local filesystem | $0 |
WebSocket | API Gateway WebSocket | In-process EventEmitter + local WS server | $0 |
AI Agent | Amazon Bedrock | Canned keyword-based provider | $0 |
Knowledge Base | Bedrock Knowledge Bases | Local TF-IDF over markdown files | $0 |
Background Jobs | Amazon SQS + Lambda | In-process queue/handler | $0 |
Logs | Amazon CloudWatch Logs | Console stdout (structured JSON) | $0 |
Metrics | Amazon CloudWatch (EMF) | Console stdout (EMF format) | $0 |
Total across all 3 apps | | | $0 |
Every AWS Block has a local mock that is API-identical to its cloud counterpart. You develop, test, and demo without ever touching AWS. When you're ready to deploy, the same code runs against real services with
npm run deploy .
Open Project - Build Your Own AWS Blocks App
This open project is a hands-on collection of AWS Blocks builds, experiments, and implementation guides. Start with the production Wellness App to understand the architecture, then explore additional AWS Blocks projects and challenges to build your own application.
How I Built a Production Wellness App Using AWS Blocks Architecture
A complete implementation showing how the same application logic can run locally and on AWS using block-based adapters, with DynamoDB, Cognito, Lambda, API Gateway, CloudFormation, and Amazon Bedrock with Nova.
What I Learned
1. Infrastructure from Code eliminates boilerplate
No CloudFormation templates, no IAM policies, no SDK wiring. You declare a
DistributedTable and call .put() / .query() . The framework handles everything else.2. Local mocks enable rapid iteration
The full dev loop is
npm run dev → edit → save → hot reload. No deploy waits, no cloud debugging, no credential rotation headaches.3. Progressive complexity maps well to Building Blocks
Complexity | You add |
|---|---|
Basic CRUD | AuthBasic + DistributedTable |
Real-time | + Realtime + conditional writes |
AI + Ops | + AuthCognito + Agent + KnowledgeBase + FileBucket + Logger + Metrics |
Each new Block snaps in without restructuring existing code.
4. Conditional writes solve concurrency
DynamoDB's conditional expressions (exposed as
ifNotExists and ifFieldEquals in AWS Blocks) handle:- One-vote-per-user (Level 2)
- Optimistic locking with revision fields (Level 2)
- Rate limiter counter increments (Level 3)
No external locks, no Redis, no distributed coordination.
5. The AI agent is just another tool-calling service
The Agent Building Block abstracts away:
- Model selection and fallback chains
- Conversation persistence
- Tool execution loops
- Streaming via Realtime
You define tools with Zod schemas and handlers. The framework does the rest.
Running the Projects
# Clone the repositorygit clone <repo-url>cd aws-blocks-skill-sprint
# Level 1 — Bookmark Managercd level-1-personal-bookmark-managernpm install && npm run dev
# Level 2 — Live Pollscd level-2-live-pollsnpm install && npm run dev
# Level 3 — AI Help Deskcd level-3-ai-help-desknpm install && npm run dev
Resources
Resource | Link |
|---|---|
AWS Blocks Documentation | https://docs.aws.amazon.com/blocks/latest/devguide/what-is-blocks.html |
AWS Blocks npm Package | https://www.npmjs.com/package/@aws-blocks/blocks |
AWS Blocks YouTube Session | https://www.youtube.com/watch?v=9ch17B2QQqk\&t=5487s |
Kiro IDE (with AWS Blocks Power) | https://kiro.dev |
Node.js 22 | https://nodejs.org |
Zod Schema Validation | https://zod.dev |
Conventional Commits | https://www.conventionalcommits.org |
Summary
| Level 1 | Level 2 | Level 3 |
|---|---|---|---|
App | Bookmark Manager | Live Polls | AI Help Desk |
Users | Single-role | Single-role | Multi-role (customer + agent) |
Data | 1 table | 2 tables | 3 tables |
Auth | AuthBasic | AuthBasic | AuthCognito + groups |
Realtime | No | Yes | Yes (agent-only) |
AI | No | No | Yes (Agent + KnowledgeBase) |
Files | No | No | Yes (FileBucket) |
Background | No | AsyncJob | No |
Observability | No | No | Logger + Metrics |
Concurrency | No | Conditional writes + revision | Conditional writes + rate limiter |
AWS Cost | $0 | $0 | $0 |
Lines of Backend | ~60 | ~200 | ~300 |
Built during the AWS Builders Skill Sprint - DevTools Month, 2026
Thank you for taking the time to read my article! If you found it helpful, feel free to like, share, and drop your thoughts in the comments; I’d love to hear from you.
If you want to connect or dive deeper into cloud, AI and DevOps, feel free to follow me on my socials:
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article