1. Context and scale
This blueprint serves a public static website and a small API from one CloudFront distribution. The example product is a documentation and support site: visitors read cached pages, and authenticated users submit feedback. The API stores submissions in PostgreSQL and schedules asynchronous work, such as notifications, through a queue.
The architecture is deliberately a handful of managed components rather than a service mesh or a fleet of containers. CloudFront is the public entry point. S3 holds versioned static assets; API Gateway routes uncached API requests to Lambda; and a multi-AZ relational database stores transactional records. Lambda@Edge has one narrow job: normalize static-site paths before CloudFront fetches an object. It is not the API compute layer.
Assumptions for sizing, not measured production limits:
| Dimension | Assumption |
|---|---|
| Users | 50,000 daily active users; within the requested 10,000–100,000 daily-user range |
| Requests/s | 20 requests/s average and 250 requests/s short peak across page and API traffic |
| Data volume | 150 GB of versioned static assets; 100 GB of transactional data initially; under 10 GB of new records per month |
| Team size | One team of 5–7 engineers, including shared platform and operations responsibilities |
| Budget | A target of roughly $500–$1,000/month for this workload, excluding labor, taxes, support plans, and unusual transfer or logging volume |
Those figures are planning inputs, not promises about capacity or cost. Before launch, validate peak traffic, response sizes, database growth, and regional prices against the real workload. The design assumes one AWS Region for the application, CloudFront’s global edge network for delivery, and a staging environment that is separate from production.
2. Requirements
The application needs a fast public site, a protected write API, and reliable asynchronous follow-up work. The API is small enough to remain a modular Lambda application; splitting it into services would add deployment and operational boundaries without a clear benefit.
Functional requirements:
| Area | Requirement |
|---|---|
| Static delivery | Serve versioned HTML, JavaScript, CSS, images, and documents from a private S3 bucket through CloudFront |
| Routing | Resolve clean paths such as /guide/install to a static document without sending static requests to the API |
| API | Accept authenticated feedback submissions and expose a small set of read and write endpoints |
| Persistence | Store submissions and delivery state transactionally in PostgreSQL |
| Asynchronous work | Queue notifications or other non-critical side effects; retry failed work without losing the original submission |
| Release | Promote tested artifacts through staging and production with controlled cache invalidation |
Non-functional requirements:
| Concern | Requirement |
|---|---|
| Availability | Target 99.9% monthly availability for API requests; static delivery should remain available when the database is impaired |
| Latency | Keep cached static delivery at the edge; set an API p95 target of 500 ms for ordinary requests, excluding slow downstream dependencies |
| Security | Use TLS, private S3 access, authenticated writes, least-privilege IAM, and edge and API-layer request filtering |
| Consistency | A successful submission response means the record and its outbox event have committed; notification delivery is eventually consistent |
| Resilience | Isolate asynchronous failures from user requests, use a multi-AZ database, and retain recoverable database backups |
| Operability | Correlate API logs and traces, measure user-visible SLIs, and alert on actionable symptoms rather than every transient error |
These targets are starting points. In particular, p95 latency and availability should be confirmed against product requirements and measured from representative clients.
3. High-level design
The browser resolves the site’s hostname to CloudFront. A CloudFront distribution has separate behaviors: the default behavior serves static content from a private S3 origin, while /api/* goes to a regional API Gateway HTTP API origin. The static behavior invokes Lambda@Edge on viewer requests to normalize paths. The API behavior does not invoke that function and is not cached.
The API authorizes requests using a Cognito user pool JWT authorizer, then invokes a Node.js Lambda function. That function writes to RDS for PostgreSQL through RDS Proxy. The API transaction creates both the submission and an outbox row. A scheduled dispatcher reads committed outbox records and sends work to SQS; a worker Lambda processes messages idempotently.
flowchart LR
User["Browser"] --> WAF["AWS WAF"]
WAF --> CF["Amazon CloudFront"]
CF --> Edge["Lambda@Edge path normalizer"]
Edge --> S3["Private Amazon S3 bucket"]
CF --> APIGW["Amazon API Gateway HTTP API"]
APIGW --> Auth["Amazon Cognito JWT authorizer"]
Auth --> API["AWS Lambda API"]
API --> Proxy["Amazon RDS Proxy"]
Proxy --> DB["Amazon RDS for PostgreSQL Multi-AZ"]
DB --> Dispatch["EventBridge Scheduler and dispatcher Lambda"]
Dispatch --> Queue["Amazon SQS"]
Queue --> Worker["Worker Lambda"]The default CloudFront behavior serves static objects; /api/* bypasses the edge rewrite and cache.
AWS WAF protects the CloudFront distribution, and a regional web ACL can protect the API Gateway stage independently. This matters because a CloudFront-only web ACL does not prevent clients from calling a public API Gateway endpoint directly. JWT validation, API Gateway throttling, and application-level authorization must remain effective on that direct path.
Use CloudFront Origin Access Control (OAC) for S3, not a public bucket. The API origin uses a cache policy that disables caching and an origin request policy that forwards only the headers, query strings, and cookies the API needs. Avoid forwarding every viewer value by default: it can reduce cache efficiency on static paths, increase origin exposure, and make request behavior harder to reason about.
4. Cloud service mapping
The equivalents below are architectural correspondences, not claims of identical feature sets. In particular, edge compute and managed database deployment models differ across providers.
| Responsibility | AWS choice | Azure equivalent or closest pattern | GCP equivalent or closest pattern |
|---|---|---|---|
| CDN and TLS termination | Amazon CloudFront | Azure Front Door | Cloud CDN with an external Application Load Balancer |
| Static object origin | Private Amazon S3 bucket with OAC | Azure Blob Storage with private origin access | Cloud Storage with a private or load-balancer-controlled origin |
| Lightweight edge logic | Lambda@Edge | Front Door rules for simple rewrites; use an origin function for general code | Cloud CDN routing features for simple rules; use an origin service for general code |
| API ingress | API Gateway HTTP API | Azure API Management or an HTTP ingress in front of Functions | API Gateway or an HTTPS load-balanced backend |
| API compute | AWS Lambda | Azure Functions | Cloud Run functions or Cloud Run |
| User authentication | Amazon Cognito user pools | Microsoft Entra External ID | Identity Platform |
| Transactional database | RDS for PostgreSQL, Multi-AZ | Azure Database for PostgreSQL Flexible Server with zone redundancy | Cloud SQL for PostgreSQL with high availability |
| Connection pooling | Amazon RDS Proxy | PgBouncer or an appropriate managed database proxy pattern | Cloud SQL Auth Proxy and connection pooling |
| Background queue | Amazon SQS | Azure Service Bus queues | Cloud Tasks or Pub/Sub, depending on delivery semantics |
| Scheduled dispatch | EventBridge Scheduler | Azure Functions timer trigger | Cloud Scheduler |
| Edge and API filtering | AWS WAF | Azure Web Application Firewall | Cloud Armor |
| Logs and metrics | CloudWatch; OpenTelemetry instrumentation | Azure Monitor and OpenTelemetry | Cloud Logging, Cloud Monitoring, and OpenTelemetry |
Lambda@Edge is intentionally not used as a general-purpose API backend. Its deployment and runtime constraints make it a poor place for database access, secret retrieval, or business workflows. Keep edge logic small, deterministic, and independent of application state.
5. Data design
This is an operational data model, not an analytics warehouse. PostgreSQL is the source of truth for submissions and for whether asynchronous work has been dispatched. The outbox table prevents the classic dual-write failure in which a database commit succeeds but queue publication fails.
A scheduled dispatcher claims pending rows, sends messages to SQS, and records delivery state. If it crashes after sending but before updating the row, it may send the message again. The worker therefore treats event_id as an idempotency key. A dead-letter queue retains messages that exceed the retry policy; it does not replace monitoring or a replay procedure.
erDiagram
SUBMISSION ||--o{ OUTBOX_EVENT : produces
SUBMISSION {
uuid id PK
varchar subject_id
varchar idempotency_key
text message
timestamptz created_at
}
OUTBOX_EVENT {
uuid id PK
uuid submission_id FK
varchar event_type
jsonb payload
timestamptz created_at
timestamptz published_at
}The outbox is committed with the submission so that queued work can be recovered after a dispatch failure.
A compact PostgreSQL schema can start with these tables and indexes:
CREATE TABLE submission (
id uuid PRIMARY KEY,
subject_id varchar(200) NOT NULL,
idempotency_key varchar(200) NOT NULL,
message text NOT NULL CHECK (length(message) <= 10000),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (subject_id, idempotency_key)
);
CREATE TABLE outbox_event (
id uuid PRIMARY KEY,
submission_id uuid NOT NULL REFERENCES submission(id),
event_type varchar(100) NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_pending_idx
ON outbox_event (created_at)
WHERE published_at IS NULL;
CREATE INDEX submission_subject_created_idx
ON submission (subject_id, created_at DESC);
Do not store identity-provider access tokens or unnecessary profile data in these tables. Use the authenticated subject identifier from the validated JWT as the ownership key. Set a retention policy for old submissions and outbox rows, and ensure it matches product and regulatory requirements before implementing automatic deletion.
6. Low-level design
The edge function rewrites only the URI for static requests. It does not make network calls or attempt authentication. CloudFront selects the behavior before invoking the associated function, so configure the function only on the default static behavior; the /api/* behavior should not associate it.
The first example is a minimal, dependency-free path normalizer. It maps a clean route to an HTML object while leaving files and API paths untouched.
type EdgeRequest = {
uri: string;
};
export function rewriteStaticUri(request: EdgeRequest): EdgeRequest {
if (request.uri.startsWith("/api/")) return request;
const isFile = /\.[a-zA-Z0-9]+$/.test(request.uri);
if (!isFile && !request.uri.endsWith("/")) {
request.uri += "/";
}
if (request.uri.endsWith("/")) {
request.uri += "index.html";
}
return request;
}
export const handler = async (event: any) => {
const request = event.Records[0].cf.request;
return rewriteStaticUri(request);
};
Notice that the rewrite is deterministic and changes only uri; CloudFront behavior selection and API routing remain separate.
The API handler below assumes API Gateway has validated the JWT and that the database credentials are supplied to the Lambda runtime through an approved secret-management and rotation process. It writes the submission and outbox event in one transaction. In production, package pg, configure connection limits deliberately, and use RDS Proxy to reduce connection churn.
import { randomUUID } from "node:crypto";
import { Pool } from "pg";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 4,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 2_000,
});
export const handler = async (event: any) => {
const subjectId = event.requestContext?.authorizer?.jwt?.claims?.sub;
const idempotencyKey = event.headers?.["idempotency-key"];
const body = JSON.parse(event.body ?? "{}");
const message = typeof body.message === "string" ? body.message.trim() : "";
if (!subjectId || !idempotencyKey || message.length === 0 || message.length > 10_000) {
return { statusCode: 400, body: JSON.stringify({ error: "invalid_request" }) };
}
const client = await pool.connect();
const submissionId = randomUUID();
const eventId = randomUUID();
try {
await client.query("BEGIN");
const result = await client.query(
`INSERT INTO submission (id, subject_id, idempotency_key, message)
VALUES ($1, $2, $3, $4)
ON CONFLICT (subject_id, idempotency_key) DO NOTHING
RETURNING id`,
[submissionId, subjectId, idempotencyKey, message],
);
if (result.rowCount === 0) {
const existing = await client.query(
`SELECT id FROM submission WHERE subject_id = $1 AND idempotency_key = $2`,
[subjectId, idempotencyKey],
);
await client.query("COMMIT");
return { statusCode: 200, body: JSON.stringify({ id: existing.rows[0].id }) };
}
await client.query(
`INSERT INTO outbox_event (id, submission_id, event_type, payload)
VALUES ($1, $2, $3, $4::jsonb)`,
[eventId, submissionId, "submission.created", JSON.stringify({ submissionId })],
);
await client.query("COMMIT");
return { statusCode: 202, body: JSON.stringify({ id: submissionId }) };
} catch {
await client.query("ROLLBACK");
return { statusCode: 500, body: JSON.stringify({ error: "internal_error" }) };
} finally {
client.release();
}
};
Notice that retries with the same subject and idempotency key return the existing resource instead of creating another submission.
The example intentionally keeps response details generic. Production code should validate content type and request size, avoid returning raw database errors, and emit a structured error with a correlation identifier. Ensure the Lambda timeout is shorter than the API Gateway integration timeout, and bound database connections across all concurrent Lambda environments.
Represent the API as modules inside one deployable application: request validation, authorization policy, submission service, repository, and outbox dispatch. Keep the dispatcher and queue worker separate Lambda entry points so their retry and concurrency policies can evolve independently, but do not split the user-facing API into multiple services without a demonstrated ownership or scaling need.
7. Key flows
A static request is answered from CloudFront when the object is cached. On a miss, the edge rewrite runs before the S3 origin fetch. Versioned asset names allow long-lived caching, while HTML uses a shorter lifetime so a release can point clients at the new asset set.
sequenceDiagram
participant B as Browser
participant W as AWS WAF
participant C as CloudFront
participant L as Lambda@Edge
participant S as Private S3
B->>W: GET /guide/install
W->>C: Allow request
C->>C: Check static cache
C->>L: Viewer request on cache miss
L->>C: Rewrite URI to /guide/install/index.html
C->>S: Fetch object through OAC
S->>C: HTML object
C->>B: Cached HTML responseThe edge rewrite applies to a static behavior and does not turn the API path into a static object lookup.
A feedback submission is accepted only after authentication and a database transaction. Queue work happens after the response path, so a slow notification provider does not hold the user request open. The outbox dispatcher and worker must both tolerate duplicate delivery.
sequenceDiagram
participant B as Browser
participant C as CloudFront
participant G as API Gateway
participant A as API Lambda
participant D as RDS PostgreSQL
participant P as Dispatcher Lambda
participant Q as SQS
participant X as Worker Lambda
B->>C: POST /api/submissions
C->>G: Forward uncached request
G->>G: Validate Cognito JWT
G->>A: Invoke authenticated request
A->>D: Commit submission and outbox event
D->>A: Commit successful
A->>B: 202 Accepted
P->>D: Read pending outbox events
P->>Q: Send event message
P->>D: Mark event published
Q->>X: Deliver message
X->>X: Process idempotentlyThe API acknowledges durable database acceptance; queue processing has its own retry and failure policy.
8. Build and release
Use Terraform or CDK to manage the distribution, buckets, policies, API, database, queues, and monitoring. Keep application artifacts separate from infrastructure state. The following Terraform excerpt shows the important edge and origin pattern; it is a focused example, not a complete production stack. The Lambda@Edge function must be published in us-east-1, and CloudFront must reference a versioned function ARN rather than $LATEST.
provider "aws" {
region = var.region
}
provider "aws" {
alias = "use1"
region = "us-east-1"
}
resource "aws_s3_bucket" "site" {
bucket = var.site_bucket_name
}
resource "aws_s3_bucket_public_access_block" "site" {
bucket = aws_s3_bucket.site.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_cloudfront_origin_access_control" "site" {
name = "site-oac"
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
resource "aws_iam_role" "edge" {
provider = aws.use1
name = "static-path-rewriter"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
Service = ["lambda.amazonaws.com", "edgelambda.amazonaws.com"]
}
Action = "sts:AssumeRole"
}]
})
}
resource "aws_iam_role_policy_attachment" "edge_logs" {
provider = aws.use1
role = aws_iam_role.edge.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
resource "aws_lambda_function" "edge" {
provider = aws.use1
function_name = "static-path-rewriter"
role = aws_iam_role.edge.arn
runtime = "nodejs22.x"
handler = "index.handler"
filename = "${path.module}/artifacts/edge.zip"
publish = true
}
resource "aws_cloudfront_distribution" "site" {
enabled = true
origin {
domain_name = aws_s3_bucket.site.bucket_regional_domain_name
origin_id = "private-site"
origin_access_control_id = aws_cloudfront_origin_access_control.site.id
}
default_cache_behavior {
target_origin_id = "private-site"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD", "OPTIONS"]
cached_methods = ["GET", "HEAD"]
cache_policy_id = var.static_cache_policy_id
lambda_function_association {
event_type = "viewer-request"
lambda_arn = aws_lambda_function.edge.qualified_arn
include_body = false
}
}
# Add an /api/* behavior with the API Gateway origin, caching disabled,
# and no Lambda@Edge association.
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
acm_certificate_arn = var.cloudfront_certificate_arn
ssl_support_method = "sni-only"
minimum_protocol_version = "TLSv1.2_2021"
}
}
Notice that the edge function is published from us-east-1; the certificate used by CloudFront must also be in us-east-1.
The complete Terraform should also include the CloudFront bucket policy restricted to the distribution’s OAC, a DNS record, WAF associations, an API origin and /api/* behavior, RDS Proxy and database subnet/security-group rules, encryption keys where required, access logs, alarms, and state locking. Pin provider versions and review plan output; do not let a CI job apply an unreviewed production plan.
A GitHub Actions workflow can build, test, and deploy to staging on ordinary changes, then gate production promotion behind an approval environment. Configure AWS access with GitHub OIDC and a narrowly scoped IAM role rather than long-lived access keys.
name: site-api-release
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
id-token: write
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build
- run: npm run test:integration
deploy-staging:
if: github.event_name == 'push'
needs: test
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION }}
- run: npm ci && npm run build
- run: terraform init -input=false
- run: terraform apply -auto-approve -input=false -var-file=staging.tfvars
- run: npm run smoke:staging
deploy-production:
if: github.event_name == 'push'
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION }}
- run: npm ci && npm run build
- run: npm run deploy:production
- run: npm run smoke:production
Notice that production promotion occurs only after staging smoke tests and environment approval; separate the production deployment implementation and role from staging in a real repository.
Test the system at the boundaries that can fail:
- Unit: path rewriting, validation, authorization policies, idempotency behavior, outbox state transitions, and worker duplicate handling.
- Integration: PostgreSQL transactions and constraints, RDS Proxy connectivity, SQS delivery and redrive behavior, API Gateway authorizer behavior, and S3 OAC access.
- Contract: OpenAPI request and response schemas, error shapes, JWT claims used by the API, and the message schema consumed by the worker.
- Load: realistic static cache-hit and cache-miss traffic, API concurrency, database connection pressure, and queue backlog recovery. Test gradual ramp-up and short bursts, not only a single sustained rate.
- Release: verify hashed assets, HTML cache headers, API non-caching, rollback behavior, and CloudFront propagation before declaring a release complete.
9. Observability
Instrument the API and worker with OpenTelemetry, then export traces and metrics through a supported Lambda instrumentation setup, such as an AWS Distro for OpenTelemetry Lambda layer. Instrumentation is useful only if the deployment also configures an exporter and a destination. Keep CloudFront and API Gateway access logs enabled with retention and sampling choices that fit the privacy and cost requirements.
Log one structured event per meaningful application outcome. Include a request or trace identifier, route template, status, duration, and result category. Do not log authorization headers, raw JWTs, full submission messages, database connection strings, or other secrets.
{
"timestamp": "2026-11-14T12:00:00.000Z",
"level": "INFO",
"service": "feedback-api",
"route": "POST /api/submissions",
"request_id": "req-7e91",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"status_code": 202,
"duration_ms": 38,
"outcome": "accepted",
"submission_id": "2c35f8a4-9cdb-4bf8-a761-a803e1738425"
}
Use identifiers for correlation while excluding user-provided content and credentials.
A manual span is useful for business-level visibility around the database transaction. This code assumes the Lambda runtime has an initialized OpenTelemetry SDK and exporter; the API package alone does not export traces.
import { trace, SpanStatusCode } from "@opentelemetry/api";
const tracer = trace.getTracer("feedback-api");
export async function createSubmissionWithSpan<T>(
operation: () => Promise<T>,
): Promise<T> {
return tracer.startActiveSpan("submission.persist", async (span) => {
try {
const result = await operation();
span.setAttribute("app.outcome", "accepted");
return result;
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR });
span.recordException(error as Error);
throw error;
} finally {
span.end();
}
});
}
Notice that the span describes an application operation without recording message contents or other high-cardinality data.
Track RED metrics for services: request rate, error rate, and duration for API Gateway, API Lambda, and worker Lambda. Track USE metrics for resources: utilization, saturation, and errors for the database, RDS Proxy, SQS, and Lambda concurrency. Useful additional signals include CloudFront cache-hit ratio, origin latency, outbox age, queue age, and dead-letter queue depth.
| SLI | Measurement | Initial SLO |
|---|---|---|
| API availability | Successful eligible API requests divided by eligible requests, excluding client validation errors | 99.9% monthly |
| API latency | Eligible API requests completed in 500 ms or less | 95% monthly |
| Static availability | Successful CloudFront static responses, excluding expected client errors | 99.95% monthly |
| Async freshness | Accepted submissions whose notification work completes within 5 minutes | 99% monthly |
These are starting objectives, not guarantees. Exclude planned maintenance only if the product’s SLO policy explicitly allows it; do not silently remove inconvenient incidents from the denominator.
Dashboards should show CloudFront requests, cache-hit ratio and origin errors; API request volume, errors and latency; Lambda throttles, errors and concurrency; database connections, CPU, storage and failovers; and queue depth, oldest-message age, and dead-letter count. Page on sustained API error-budget burn, a rapidly growing queue that violates the freshness SLO, database unavailability or connection exhaustion, repeated Lambda throttling that causes user-visible errors, and sustained static origin failures. Notify rather than page on isolated edge errors or a single retryable message failure.
10. Security and compliance
Treat CloudFront as the public boundary, not as a substitute for authorization. Configure TLS-only viewer access, AWS WAF managed protections with tested exclusions, rate-based rules, and separate API Gateway throttling. The API must validate identity and ownership for every protected operation, including when a client bypasses CloudFront and calls API Gateway directly.
Use a private S3 bucket with Block Public Access and OAC. Scope the bucket policy to the CloudFront distribution. Use least-privilege IAM roles per function: the API can access only its required secret and database connectivity; the dispatcher can read and update outbox records and send to its queue; the worker can consume from its queue and access only the dependencies it needs.
Store database credentials in a managed secret store and rotate them through a tested process. Encrypt the database, SQS queues, logs where required, and backups at rest. Use private database subnets, security-group rules that allow only the proxy and required management paths, and a TLS connection between the application and database. Avoid placing credentials or customer data in Lambda@Edge code: edge deployments are replicated and have a different operational profile from regional application functions.
The Lambda@Edge function must be published in us-east-1 and associated with a numbered version. Keep it small, review its runtime and feature restrictions before choosing dependencies, and test behavior against CloudFront’s actual event format. Restrict who can publish or associate edge versions; a small code change can affect every viewer.
For compliance, identify the applicable obligations before choosing retention, access logging, encryption-key ownership, and data-residency controls. CloudFront and Lambda@Edge execute across edge locations, so do not put regulated data in edge code or assume that an edge function provides regional data residency. Define deletion, audit access, incident response, and backup-retention procedures as operational controls, not just infrastructure settings.
11. Cost
The following is an assumption-based monthly estimate, not a price quote. It assumes one production workload in one AWS Region, a moderate static footprint, 50,000 daily users, 1 TB/month of CloudFront data transfer to viewers, limited API writes, and no unusual log retention or cross-region replication. Public pricing changes and depends on region, request mix, transfer destination, and selected capacity. Validate the actual design with the AWS Pricing Calculator before committing to a budget.
| Cost area | Monthly planning range | Main cost drivers |
|---|---|---|
| CloudFront | $100–$300 | Viewer transfer, request volume, cache misses, logs, and invalidations |
| RDS PostgreSQL Multi-AZ and RDS Proxy | $200–$450 | Instance class, storage, backups, proxy capacity, and I/O |
| API, dispatcher, and worker Lambda | $20–$100 | Invocations, duration, memory, concurrency, and retries |
| API Gateway and SQS | $10–$60 | API requests, queue operations, and dead-letter/replay activity |
| S3, CloudWatch, WAF, and related services | $40–$150 | Object storage, log ingestion and retention, WAF rules, and monitoring |
| Estimated total | $370–$1,060 | Excludes taxes, support, domain registration, and exceptional transfer |
The database is the main fixed-cost component in this design because it provides managed relational storage with multi-AZ availability. CloudFront traffic and log ingestion can vary substantially. Put budgets and anomaly alerts in place, apply lifecycle rules to non-current static assets where appropriate, set explicit log retention, and measure cache effectiveness before tuning TTLs. Do not reduce database resilience or observability solely to meet an unvalidated estimate.
12. Failure modes, resilience and disaster recovery
A single-region application with a multi-AZ database is designed for availability-zone failures, not automatic regional survival. Be explicit about that boundary. The static site can continue to serve cached objects during some regional application failures, but API writes depend on the regional API and database.
| Failure mode | User impact | Response |
|---|---|---|
| S3 origin or object error | Static cache misses fail; already cached objects may remain available | Alert on origin errors; deploy immutable assets before updating HTML; retain the last known-good release |
| Lambda@Edge deployment or rewrite defect | Clean static paths may return errors or wrong objects | Use a small function, test CloudFront events, publish immutable versions, and keep a tested rollback procedure |
| API Lambda errors or throttling | Writes fail or slow down | Bound concurrency and retries, alarm on user-visible errors, and return retry-safe responses |
| Database or proxy impairment | API persistence fails; queue work may stop | Use Multi-AZ deployment, connection limits, health alarms, and documented failover behavior |
| Dispatcher outage | Outbox age increases, but accepted submissions remain stored | Alert on oldest pending event; resume dispatch after repair and process safely with idempotency |
| Queue worker failure | Notifications are delayed or moved to the DLQ | Redrive after fixing the cause; monitor queue age and DLQ depth; keep worker side effects idempotent |
| Regional outage | API and database are unavailable in the application region | Restore or fail over using a tested regional recovery plan; communicate the expected recovery time |
Set database backups and point-in-time recovery according to the recovery point objective, and periodically test restoration into an isolated environment. A backup that has not been restored is an assumption, not evidence of recoverability. Define recovery time and recovery point objectives with the business; do not label the single-region design multi-region disaster recovery.
For a regional recovery option, replicate static assets to a second region and prepare infrastructure there, but keep the initial operational model simple. Database recovery is the harder decision: a cross-region replica can reduce recovery time but introduces replication lag, promotion steps, and possible data loss. Document DNS or CloudFront origin changes, database promotion, secret availability, queue handling, and verification steps. Run a tabletop exercise before claiming regional readiness.
13. Evolving to the next scale
Do not scale components because a daily-user count crossed a round number. Change the design when a measured limit, reliability objective, or team boundary justifies the added complexity.
| Signal | Next change | Why it helps |
|---|---|---|
| Cache misses or origin load dominate static delivery | Tune cache keys and TTLs; separate frequently changing content from immutable assets | Reduces origin traffic without changing the application topology |
| API database load or connection pressure is sustained | Optimize queries and indexes, review pool sizing, then consider read replicas for read-heavy endpoints | Addresses the measured bottleneck while preserving transactional writes |
| Outbox backlog is regularly outside its freshness SLO | Increase dispatcher/worker concurrency within downstream limits; partition or shard work only when contention is demonstrated | Improves recovery and throughput without making the API synchronous |
| API releases have conflicting ownership or change cadence | Split modules into independently owned services around stable boundaries | Creates meaningful deployment autonomy rather than merely more Lambda functions |
| One-region recovery objectives are insufficient | Add a tested second-region deployment and explicit database failover strategy | Extends the failure boundary with measurable recovery behavior |
| Edge logic becomes stateful or business-heavy | Move it to regional application services; retain only deterministic routing at the edge | Avoids putting secrets, data access, and complex policy into a globally distributed hook |
Lambda@Edge should not become the default location for new behavior. For simple redirects or header manipulation, compare it with CloudFront Functions, which can be a better fit for lightweight viewer-side logic. Keep Lambda@Edge when its runtime capabilities are actually needed, and measure the operational cost of maintaining a separately deployed global function.
14. Phased implementation plan
A small team can deliver this architecture in increments, validating the risky boundaries before building operational polish around them.
- Confirm product and traffic assumptions. Agree on API authentication, data retention, availability objectives, expected request sizes, and regional recovery expectations. Turn the assumptions table into a reviewable capacity and budget plan.
- Build static delivery first. Create the private S3 bucket, OAC, CloudFront distribution, DNS, TLS, cache policies, and a static-site release. Verify that direct S3 access is denied and that asset versioning and HTML cache headers behave as intended.
- Add the edge rewrite. Implement the minimal path normalizer, publish a numbered version from
us-east-1, associate it only with the static behavior, and test clean routes, asset paths, and API paths through CloudFront. - Implement the API and data boundary. Add API Gateway, JWT validation, the Lambda application, RDS Proxy, multi-AZ PostgreSQL, schema migrations, and the transactional outbox. Test authorization, request validation, idempotent retries, and database failover behavior in staging.
- Add asynchronous processing. Deploy the dispatcher, SQS queue and dead-letter queue, and idempotent worker. Test duplicate messages, delayed processing, poison messages, and replay procedures before enabling production notifications.
- Automate release and operations. Add OIDC-based CI/CD, gated promotion, CloudFront invalidation only where required, structured logs, OpenTelemetry instrumentation, dashboards, SLO reporting, and symptom-based alerts. Run a load test and a database restore exercise.
- Review readiness and ownership. Record runbooks for deployment rollback, queue replay, credential rotation, incident response, and database recovery. Confirm who is paged, who approves production changes, and which measured conditions trigger the next architecture review.
The resulting system is intentionally modest: a CDN-backed static site, a small regional API, one transactional database, and a queue for work that should not block the user. The important architectural boundary is not “edge versus serverless.” It is keeping globally distributed request rewriting separate from authenticated business logic and durable state.
This article was generated with AI. #AIGenerated