Safety Rails & Denial-of-Wallet Shield
The primary reason teams pay a 10x–50x PaaS tax on Vercel or Render isn't developer ergonomics—it is fear of an unbounded AWS bill.
On standard AWS (raw CDK, SAM, or Serverless Framework), concurrency defaults to account-wide limits (1,000+ instances), event streams retry for 24 continuous hours without dead-letter queues, and log groups never expire. A single accidental stream loop or public scraping flood can burn a $10,000+ credit limit overnight while CloudFormation deploys without a single warning.
Syncploy embeds a Pre-Flight Safety Engine directly into the compiler. In $<1\text{ms}$ during Abstract Syntax Tree (AST) parsing, Syncploy models the infrastructure topology as a directed graph, verifies mathematical blast-radius bounds, detects event cycles, and halts compilation before any resources can be synthesized or deployed.
---
1. Why Runtime Billing Alarms Fail#
Most engineering teams rely on AWS CloudWatch Billing Alarms or AWS Budgets. These are post-mortem notifications, not preventative guardrails:
| Feature | AWS CloudWatch Billing Alarm | Syncploy Pre-Flight Shield |
|---|---|---|
| Enforcement Point | Post-execution (15 to 45 min delay) | Pre-flight AST compilation (<1ms) |
| Mitigation Action | Sends an email or SNS alert | Aborts compilation; 0 resources synthesized |
| Protection While Sleeping | ❌ None. Bill continues to surge until human intervention | ✅ Total. Unbounded code cannot deploy to AWS |
| Native Circuit Breaker | ❌ None. AWS provides no native auto-shutdown | ✅ Mathematical. Hardware compute liabilities hard-capped |
---
2. The Mathematical Blast-Radius Guarantee#
Denial-of-Wallet cannot be solved with rate limiting alone—rate limiters can be bypassed, spoofed, or misconfigured. True financial immunity requires mathematically bounding hardware liabilities in code.
Even if an unauthenticated endpoint is targeted by an unmitigated 500,000,000-request DDoS flood, its monthly compute spend cannot physically exceed the ceiling of its assigned resources:
$$\text{Max Monthly Compute} = \text{Concurrency} \times \frac{\text{Memory MB}}{1024} \times 2,592,000\text{s} \times \$0.0000166667$$
Hardware Ceiling Reference#
| Reserved Concurrency | Memory Allocation | Worst-Case Sustained 24/7 Spend | Standard AWS Default (1,000 Concurrency) |
|---|---|---|---|
| 2 | 128 MB | $10.80 / mo | $5,400.00 / mo |
| 5 | 256 MB | $54.00 / mo | $10,800.00 / mo |
| 10 | 512 MB | $216.00 / mo | $21,600.00 / mo |
| 25 | 1024 MB | $1,080.00 / mo | $43,200.00 / mo |
Syncploy rule WARN_DOW_UNRESERVED_CONCURRENCY statically requires an explicit concurrency cap on all public Function URLs and API routes:
// ❌ HAZARDOUS (Standard AWS): Scales to 1,000+ account instances under DDoS
export const webhook = api.post("/webhook", async (req) => {
return { status: "received" };
});
// ✅ IMMUNIZED (Syncploy): Hardware-bounded to $27.00/mo under 24/7 sustained DDoS
export const webhook = api.post("/webhook", { concurrency: 5, memory: "128MB" }, async (req) => {
return { status: "received" };
});---
3. Tarjan's SCC Infinite Loop Killer#
In event-driven architectures, infinite recursion loops are the #1 cause of five-figure cloud bills ($10,000+ overnight charges).
A classic failure occurs when a Lambda consumes a DynamoDB Stream and writes back to that same table. Each write produces a new stream event, creating a continuous, self-amplifying execution avalanche:
┌────────────────────────────────────────────────────────┐
│ INFINITE RECURSION CYCLE │
│ │
│ Table 'orders' ──(Stream Event)──► worker Lambda │
│ ▲ │ │
│ └───────────(table.put)──────────┘ │
└────────────────────────────────────────────────────────┘Multi-hop cycles are equally catastrophic and virtually impossible to catch in manual code review:
$$\text{Table A} \longrightarrow \text{Worker 1} \longrightarrow \text{Queue B} \longrightarrow \text{Worker 2} \longrightarrow \text{Table A}$$
How the Compiler Traps Loops in <1ms#
- Trigger Edges: Compiler maps event sources (
Table.stream,Queue.onMessage,Bucket.onObjectCreated) to consumer Lambdas. - Mutation Edges: Compiler inspects function bodies for mutation calls (
table.put,table.update,queue.send,bucket.put,topic.publish, HTTP fetch self-calls). - Graph Construction: Constructs a directed bipartite graph $G = (V, E)$ where vertices are AWS constructs and edges are async mutations.
- Tarjan's SCC Algorithm: Executes Tarjan's Strongly Connected Components algorithm in $O(V + E)$ linear time ($<1\text{ms}$).
- Immediate Compilation Abort:
✖ [ERR_RECURSIVE_LOOP] in src/workers/order-sync.ts:
• Infinite recursion loop detected:
Table 'orders' ──► Stream Consumer 'syncOrders' ──► Table 'orders'
• Cycle triggers self-amplifying Lambda executions, scaling to maximum account
concurrency within seconds.
✖ Compilation aborted. 0 AWS resources modified.---
4. The 4 Defensive Layers#
Syncploy's pre-flight compiler runs 26 deterministic safety rules across 4 operational layers:
Layer 1: Compute Blast-Radius Bounding#
- Strict Concurrency Ceilings: Public Function URLs and API routes must declare explicit concurrency bounds (
WARN_DOW_UNRESERVED_CONCURRENCY). - Stream Throttling: DynamoDB stream consumers are auto-bounded to prevent runaway concurrent batch workers (
WARN_DOW_STREAM_UNBOUNDED). - Account Quota Sentinel: Aggregates reserved concurrency across the entire stack, warning if total $\ge 900$ to prevent starvation of critical services (
WARN_DOW_CONCURRENCY_BUDGET_EXCEEDED).
Layer 2: Event-Driven Recursion & Poison-Pill Shields#
- Tarjan's SCC Cycle Detection: Statically identifies 1-hop and multi-hop recursive cycles across tables, queues, and streams (
ERR_RECURSIVE_LOOP). - SQS 6× Timeout Invariant: Enforces that queue
visibilityTimeoutis $\ge 6 \times$ consumertimeoutto eliminate duplicate processing storms (ERR_SQS_TIMEOUT_MISMATCH,WARN_SQS_VISIBILITY_TIMEOUT_SHORT). - Mandatory Dead Letter Queues (DLQs): Active queues and stream consumers require DLQs (
maxReceiveCount: 3) to isolate poison-pill records instead of retrying for days (WARN_DOW_MISSING_DLQ). - No Table Scans: Detects
$O(N)$full-table scans in request paths to prevent crawling bots from draining Read Capacity Units (WARN_DOW_DYNAMODB_SCAN).
Layer 3: Storage & Log Leak Neutralization#
- Automatic 14-Day CloudWatch Log Rotation: Auto-synthesizes dedicated
AWS::Logs::LogGroupresources withRetentionInDays: 14for every Lambda. Eliminates default "Never Expire" log accumulation bills (INFO_DOW_LOG_ROTATION). - Automatic S3 Multipart Abort: Attaches
AbortIncompleteMultipartUpload: { DaysAfterInitiation: 7 }to all buckets to purge orphan upload chunks (INFO_DOW_S3_MULTIPART_ABORT).
Layer 4: Financial Governance, Fraud Defense & Data Safety#
- AWS Budgets Ceiling: Validates
new Budget(...)constructs and ensures SNS alert topics are wired to real notification targets (WARN_DOW_BUDGET_NO_NOTIFICATION). - SMS International Toll Fraud Shield: Warns against unmonitored SNS SMS subscriptions and Cognito phone verification endpoints (
WARN_DOW_SMS_TOLL_FRAUD). - Zero Data-Loss Replacement Gatekeeper:
syncploy diff --check-replacementverifies that no stateful resource (DynamoDB table, S3 bucket) will be destroyed during updates (ERR_STATEFUL_REPLACEMENT).
---
5. Diagnostic Suppression & CI/CD Auditing#
In rare cases where recursion is intentionally bounded by application logic (such as a finite state-machine transition in DynamoDB), diagnostics can be suppressed with an explicit inline reason:
// syncploy-ignore ERR_RECURSIVE_LOOP reason="State machine terminates on status: 'COMPLETED'"
export const stateWorker = patientTable.stream({ batchSize: 10 }, async (record) => {
if (record.status !== "COMPLETED") {
await patientTable.put({ ...record, status: "COMPLETED" });
}
});Every suppressed diagnostic is verified during syncploy build and printed as an explicit audit trail in your CI/CD pipeline:
[AUDIT] 1 diagnostic suppressed:
• ERR_RECURSIVE_LOOP in src/workers/stateWorker.ts: State machine terminates on status: 'COMPLETED'Interactive Cloud Safety Rule Explorer
LIVE AUDIT CATALOG (70 RULES)Explore, filter, and inspect all compile-time safety rules, recursion loop diagnostics, and budget guardrails. Switch between hazardous patterns and safe code remediations.
Unreserved Lambda Concurrency
Public Function URL or API route has no reserved concurrency cap.
// ❌ HAZARDOUS: Unbounded scaling under DDoS
export const checkoutApi = api(
{ path: "/checkout", method: "POST", ingress: "function-url" },
async (req) => {
return Response.json({ success: true });
}
);High-Resource Public Wildcard CORS Endpoint
Public CORS endpoint allows origins ['*'] with heavy memory or duration allocations without concurrency bounds.
// ❌ HAZARDOUS: 1024MB memory + 60s timeout + wildcard CORS + no concurrency
export const processReport = api(
{
path: "/report",
method: "POST",
memory: 1024,
timeout: "60s",
cors: { allowOrigins: ["*"] },
},
async (req) => { /* heavy work */ }
);Unbounded DynamoDB Stream Concurrency
DynamoDB stream consumer has no concurrency limit configured.
// ❌ HAZARDOUS: Can scale to match all table shards simultaneously
export const streamWorker = auditTable.stream(
{ batchSize: 100 },
async (record) => { /* ... */ }
);Stack Reserved Concurrency Quota Depletion
Total reserved concurrency across all functions in the stack exceeds 900 of the 1,000 default account limit.
// ❌ HAZARDOUS: Sum of reserved concurrency across services > 900
export const api1 = api({ concurrency: 500 }, ...);
export const api2 = api({ concurrency: 450 }, ...);Infinite Event Recursion Loop (Tarjan SCC)
An event consumer mutates or writes back directly or indirectly into its own event source (e.g. Table -> Stream -> Table.put).
// ❌ HAZARDOUS: Writing back to the stream source table
export const auditWorker = patientTable.stream({ batchSize: 50 }, async (record) => {
// BUG: Mutates the source table that triggered this stream!
await patientTable.put({ id: record.id, updatedAt: Date.now() });
});HTTP Self-Invocation Circular Storm
API route makes an internal fetch() call targeting its own URL path.
// ❌ HAZARDOUS: Fetching self via external HTTP
export const orderHandler = api({ path: "/orders", method: "POST" }, async (req) => {
await fetch("https://api.mycompany.com/orders", { method: "POST" });
});SQS Visibility Timeout Shorter Than Lambda Timeout
Queue visibilityTimeout is shorter than the consuming Lambda handler's timeout.
// ❌ HAZARDOUS: Visibility (30s) < Consumer Timeout (60s)
export const queue = new Queue("jobs", { visibilityTimeout: "30s" });
export const worker = queue.consumer({ timeout: "60s" }, async (msg) => { ... });Queue Visibility Timeout Below AWS 6x Safety Ratio
Queue visibilityTimeout is greater than consumer timeout, but less than the recommended 6x safety ratio.
export const queue = new Queue("orders", { visibilityTimeout: "35s" });
export const worker = queue.consumer({ timeout: "30s" }, ...);Active SQS Queue Without Dead Letter Queue (DLQ)
Active queue has consumers attached but no deadLetterQueue redrive policy.
// ❌ HAZARDOUS: Poison-pill messages will retry continuously
export const queue = new Queue("notifications", {
visibilityTimeout: "180s",
});DynamoDB Stream Without Failure Destination
Active DynamoDB stream consumer has no onFailure DLQ queue configured.
export const stream = auditTable.stream({ batchSize: 50 }, async (record) => { ... });DynamoDB Stream Unlimited Retries (-1)
DynamoDB stream consumer explicitly configured retryAttempts: -1.
export const stream = auditTable.stream({ retryAttempts: -1 }, ...);DynamoDB Full Table Scan in Request Path
API route invokes table.scan() inside its execution body.
// ❌ HAZARDOUS: Scans entire table on every HTTP GET
export const listPatients = api({ path: "/patients", method: "GET" }, async () => {
const all = await patientTable.scan();
return Response.json(all);
});Perpetual CloudWatch Log Accumulation Defense
Syncploy automatically synthesizes AWS::Logs::LogGroup with 14-day retention for every Lambda function.
// ❌ DEFAULT AWS: Creates unmanaged log group with infinite retention
export const myHandler = api({ path: "/run" }, async () => { ... });S3 Orphan Multipart Upload Cleanup
Syncploy automatically synthesizes AbortIncompleteMultipartUpload: { DaysAfterInitiation: 7 } on every bucket.
// ❌ DEFAULT AWS: Abandoned upload fragments remain stored forever
export const bucket = new Bucket("uploads");International SMS Toll Fraud Exposure
Topic has protocol: 'sms' or Cognito User Pool enables phone verification without explicit spend bounds.
// ❌ HAZARDOUS: Unmonitored SMS destination
export const auth = new Auth("portal", { signInMethod: "phone" });Continuous Monthly Liability Exceeds $100 Without Budget
Stack total continuous monthly compute liability exceeds $100, but no new Budget construct is declared.
// ❌ HAZARDOUS: High compute liability without financial alerting
export const api1 = api({ concurrency: 100 }, ...); // ~$108/mo liabilityBudget Amount Missing or Invalid
Budget construct has missing, zero, or non-static amount literal.
export const budget = new Budget("cap", { amount: 0 });Budget Alert Threshold Invalid
Budget threshold must be a positive number literal representing a percentage (e.g. 80).
export const budget = new Budget("cap", { amount: 50, threshold: -10 });Budget Currency Unit Not ISO Code
Budget unit must be a 3-letter uppercase ISO currency code (e.g. 'USD', 'EUR', 'GBP').
export const budget = new Budget("cap", { amount: 50, unit: "dollars" });Budget Stack Filter Invalid
Budget filterByStack must be a static boolean literal (true | false).
export const budget = new Budget("cap", { amount: 50, filterByStack: "yes" as any });Duplicate Budget Identifier Declared
Two Budget constructs share the same constructor identifier.
export const b1 = new Budget("monthly-cap", { amount: 50 });
export const b2 = new Budget("monthly-cap", { amount: 100 });Duplicate Physical AWS Budget Name
Two Budget constructs specify the same physical budgetName.
export const b1 = new Budget("b1", { amount: 50, budgetName: "my-budget" });
export const b2 = new Budget("b2", { amount: 100, budgetName: "my-budget" });Silent Budget Without Alert Topic
Budget construct has no topic configured and no fallback alert topic was discovered in the stack.
// ❌ HAZARDOUS: Silent budget records spend but alerts nobody
export const budget = new Budget("cap", { amount: 50 });Stack Cost Allocation Tag Activation Required
filterByStack: true requires activating the 'StackName' cost allocation tag in the AWS Billing console.
export const budget = new Budget("cap", { amount: 50, filterByStack: true });Budget Configured Non-Existent Alert Topic
Budget topic option does not resolve to any declared Topic construct in the stack.
export const budget = new Budget("cap", { amount: 50, topic: "missingTopic" });Destructive Stateful Resource Replacement Intercepted
syncploy diff detected an update that causes CloudFormation to DESTROY and RECREATE a DynamoDB table or S3 bucket.
// ❌ HAZARDOUS: Changing physical TableName causes CloudFormation to drop the old table
export const table = new Table("ehr", { tableName: "new-table-name" });Invalid CloudFormation Logical ID
Logical IDs in CloudFormation must be alphanumeric ([A-Za-z0-9]+).
export const table = new Table("ehr-db", { logicalId: "my_invalid-table!" });CloudFormation 500 Resource Limit Exceeded
CloudFormation stacks cannot declare more than 500 resources.
// Monolithic stack with 501+ resources
CloudFormation 60 Output Limit Exceeded
CloudFormation stacks cannot declare more than 60 outputs.
// Stack declaring 61+ stack outputs
CloudFormation 1MB Template Size Limit Exceeded
Synthesized CloudFormation template JSON exceeds 1MB limit.
// Excessively bloated stack template
Invalid API Gateway Route Path
API route path must start with a forward slash ('/').
export const getDoc = api({ path: "documents", method: "GET" }, ...);CORS Allowed Origin Missing Protocol
CORS allowed origin must include protocol (e.g. 'https://' or 'http://') or be '*'.
export const myApi = api({ cors: { allowOrigins: ["example.com"] } }, ...);Function URL Custom Auth Unsupported
Lambda Function URLs only support NONE or AWS_IAM auth types, not custom authorizers.
export const route = api({ ingress: "function-url", auth: "cognito" }, ...);Function URL Rate Limiting Unsupported
Function URLs do not support token-bucket throttle settings (burst/rate limits); use API Gateway or reserved concurrency.
export const route = api({ ingress: "function-url", throttle: { rateLimit: 100 } }, ...);Invalid Lambda Memory Allocation
Lambda memory must be between 128 MB and 10,240 MB.
export const handler = api({ memory: 64 }, ...);Invalid Lambda Execution Timeout
Lambda timeout must be between 1 second and 900 seconds (15 minutes).
export const handler = api({ timeout: "1000s" }, ...);Invalid Lambda Concurrency Limit
Lambda reserved concurrency must be an integer >= 0.
export const handler = api({ concurrency: -5 }, ...);Invalid Lambda Function Name
Lambda function names must be 1-64 characters matching [a-zA-Z0-9-_]+.
export const handler = api({ functionName: "my invalid func!" }, ...);Invalid DynamoDB Table Name
DynamoDB table names must be 3-255 characters matching [a-zA-Z0-9_.-]+.
export const table = new Table("db", { tableName: "a" });DynamoDB Partition Key and Sort Key Collision
Partition key and sort key attribute names cannot be identical.
export const table = new Table("db", { partitionKey: "id", sortKey: "id" });DynamoDB Global Secondary Index Limit Exceeded
A DynamoDB table cannot exceed 20 Global Secondary Indexes.
// Table declaring 21+ global secondary indexes
DynamoDB GSI Index Name Collision
Duplicate GSI index names defined on the same DynamoDB table.
// Two GSIs both named "byStatus"
ElectroDB Entities Partition Key Inconsistency
ElectroDB entities in the same service must share the identical primary key schema (pkField and skField).
// EntityA uses pkField: "pk", EntityB uses pkField: "id" in the same service
ElectroDB Entities GSI Definition Conflict
ElectroDB entities in the same service share a GSI index name but define conflicting index key attributes.
// EntityA defines gsi1 with pk: "gsi1pk", EntityB defines gsi1 with pk: "alt_pk"
Explicit Table Schema Conflicts with ElectroDB Entity
Explicit Table construct partitionKey/sortKey does not match the ElectroDB entity's primary index key fields.
export const table = new Table("orders", { partitionKey: "orderId" }); // Entity uses "pk"Duplicate ElectroDB Entity Name in Service
Two ElectroDB entities in the same service share the exact same entity name.
// Two Entity definitions with model.entity: "user"
Invalid S3 Bucket Name
S3 bucket names must be 3-63 characters, lowercase, and cannot contain underscores.
export const bucket = new Bucket("my_bucket_name");S3 Object Lock Requires Bucket Versioning
S3 Object Lock cannot be enabled unless bucket versioning is also enabled.
export const bucket = new Bucket("audit", { objectLock: true, versioned: false });Invalid SQS Queue Name
SQS queue names must be 1-80 characters matching [a-zA-Z0-9-_]+.
export const queue = new Queue("invalid queue name!");SQS FIFO Queue Missing .fifo Suffix
SQS FIFO queues must end with the '.fifo' suffix.
export const queue = new Queue("orders", { fifo: true });Invalid SQS Visibility Timeout
SQS visibilityTimeout must be between 0 seconds and 43,200 seconds (12 hours).
export const queue = new Queue("jobs", { visibilityTimeout: "50000s" });Invalid SQS Consumer Batch Size
SQS consumer batchSize must be between 1 and 10 (or up to 10,000 for standard queues with batchWindow).
export const worker = queue.consumer({ batchSize: 50000 }, ...);SQS Dead Letter Queue Self-Cycle
A queue cannot configure itself as its own deadLetterQueue.
export const q = new Queue("jobs", { deadLetterQueue: { queue: "jobs" } });Invalid SQS DLQ maxReceiveCount
deadLetterQueue.maxReceiveCount must be an integer >= 1.
export const q = new Queue("jobs", { deadLetterQueue: { queue: dlq, maxReceiveCount: 0 } });SNS FIFO Topic Missing .fifo Suffix
SNS FIFO topics must end with the '.fifo' suffix.
export const topic = new Topic("events", { fifo: true });Invalid SNS SQS Subscription Target
SNS topic subscriber specifies an unresolved or invalid SQS queue endpoint.
topic.subscribe("invalid-sqs-target");Invalid SNS Lambda Subscription Target
SNS topic subscription target does not resolve to a valid Lambda function.
topic.subscribeFunction("nonExistentHandler");Invalid SNS Email Subscription Address
SNS email subscription specifies a malformed email address.
topic.subscribeEmail("not-an-email");Invalid SNS Firehose Subscription Target
SNS topic subscription specifies an invalid or unresolvable DeliveryStream target.
topic.subscribeDeliveryStream("missingStream");Invalid Firehose DeliveryStream Name
Firehose delivery stream names must be 1-64 characters matching [a-zA-Z0-9_.-]+.
export const stream = new DeliveryStream("invalid firehose name!");Invalid Firehose Buffer Interval
Firehose bufferInterval must be between 60 seconds and 900 seconds.
export const stream = new DeliveryStream("events", { bufferInterval: 30 });Invalid Firehose Buffer Size
Firehose bufferSize must be between 1 MB and 128 MB.
export const stream = new DeliveryStream("events", { bufferSize: 256 });Invalid DynamoDB Stream Batch Size
DynamoDB stream consumer batchSize must be between 1 and 10,000.
table.stream({ batchSize: 20000 }, ...);Cognito Password Policy minLength Below AWS Limit
Cognito UserPool passwordPolicy.minLength must be at least 6 characters.
export const auth = new Auth("users", { passwordPolicy: { minLength: 4 } });Cognito Password Minimum Length Less Than 8
Password minLength of 6 or 7 meets AWS hard floor but falls short of security best practices (8+ chars).
export const auth = new Auth("users", { passwordPolicy: { minLength: 6 } });Hardcoded Secret In Environment Variable
Literal API key, token, or secret pattern detected in Lambda environment variables.
export const api = api({ env: { STRIPE_KEY: "sk_live_1234567890" } }, ...);Malformed IAM Policy Action
IAM policy actions must match 'service:action' format (e.g. 'dynamodb:GetItem').
export const role = new Role("myRole", { actions: ["GetItem"] });Overly Permissive IAM Wildcard Action
Wildcard IAM action (e.g. '*' or 's3:*') grants broader permissions than required.
export const role = new Role("worker", { actions: ["*"] });Invalid CloudWatch Alarm Evaluation Periods
CloudWatch alarm evaluationPeriods must be an integer >= 1.
export const alarm = new Alarm("errs", { evaluationPeriods: 0 });Invalid AWS Budget Name
AWS budget names must be 1-100 characters matching [a-zA-Z0-9=+_.:@/-]+.
export const budget = new Budget("cap", { budgetName: "my invalid budget!" });