Build efficient serverless applications with Google Antigravity
# Serverless Patterns Guide for Google Antigravity
Master serverless architecture patterns for building scalable, cost-effective applications with Google Antigravity IDE.
## Lambda Function Patterns
```typescript
// functions/api-handler.ts
import { APIGatewayProxyHandlerV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { z } from "zod";
import middy from "@middy/core";
import httpJsonBodyParser from "@middy/http-json-body-parser";
import httpErrorHandler from "@middy/http-error-handler";
import validator from "@middy/validator";
import { transpileSchema } from "@middy/validator/transpile";
const createUserSchema = z.object({
name: z.string().min(1).max(100),
email: z.string().email(),
role: z.enum(["user", "admin"]).default("user")
});
type CreateUserInput = z.infer<typeof createUserSchema>;
const baseHandler: APIGatewayProxyHandlerV2 = async (event) => {
const body = event.body as unknown as CreateUserInput;
const user = await createUser(body);
return {
statusCode: 201,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: user })
};
};
export const handler = middy(baseHandler)
.use(httpJsonBodyParser())
.use(validator({ eventSchema: transpileSchema(createUserSchema) }))
.use(httpErrorHandler());
// Cold start optimization
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
// Initialize outside handler for connection reuse
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
async function createUser(input: CreateUserInput) {
const { PutCommand } = await import("@aws-sdk/lib-dynamodb");
const userId = crypto.randomUUID();
await docClient.send(new PutCommand({
TableName: process.env.USERS_TABLE,
Item: { pk: `USER#${userId}`, sk: "PROFILE", ...input, createdAt: new Date().toISOString() }
}));
return { id: userId, ...input };
}
```
## Step Functions Workflow
```typescript
// workflows/order-processing.ts
import { SFNClient, StartExecutionCommand } from "@aws-sdk/client-sfn";
interface OrderWorkflowInput {
orderId: string;
customerId: string;
items: { productId: string; quantity: number; price: number }[];
totalAmount: number;
}
export const startOrderWorkflow = async (input: OrderWorkflowInput) => {
const client = new SFNClient({});
await client.send(new StartExecutionCommand({
stateMachineArn: process.env.ORDER_STATE_MACHINE_ARN,
input: JSON.stringify(input),
name: `order-${input.orderId}-${Date.now()}`
}));
};
// Step function definition (CDK)
import * as sfn from "aws-cdk-lib/aws-stepfunctions";
import * as tasks from "aws-cdk-lib/aws-stepfunctions-tasks";
const validateOrder = new tasks.LambdaInvoke(this, "ValidateOrder", {
lambdaFunction: validateOrderFn,
outputPath: "$.Payload"
});
const processPayment = new tasks.LambdaInvoke(this, "ProcessPayment", {
lambdaFunction: paymentFn,
outputPath: "$.Payload"
});
const reserveInventory = new tasks.LambdaInvoke(this, "ReserveInventory", {
lambdaFunction: inventoryFn,
outputPath: "$.Payload"
});
const definition = validateOrder
.next(new sfn.Parallel(this, "ProcessParallel")
.branch(processPayment)
.branch(reserveInventory))
.next(new sfn.Choice(this, "CheckResults")
.when(sfn.Condition.booleanEquals("$.success", true), sendConfirmation)
.otherwise(handleFailure));
```
## Event Bridge Patterns
```typescript
// events/event-bridge.ts
import { EventBridgeClient, PutEventsCommand } from "@aws-sdk/client-eventbridge";
const eventBridge = new EventBridgeClient({});
interface DomainEvent {
source: string;
detailType: string;
detail: Record<string, unknown>;
}
export const publishEvent = async (event: DomainEvent) => {
await eventBridge.send(new PutEventsCommand({
Entries: [{
Source: event.source,
DetailType: event.detailType,
Detail: JSON.stringify(event.detail),
EventBusName: process.env.EVENT_BUS_NAME
}]
}));
};
// Event handler
export const orderEventHandler = async (event: { detail: OrderEvent }) => {
const { detail } = event;
switch (detail.type) {
case "ORDER_PLACED":
await notifyWarehouse(detail);
await updateAnalytics(detail);
break;
case "ORDER_SHIPPED":
await notifyCustomer(detail);
break;
}
};
```
## Best Practices
1. **Minimize cold starts** with provisioned concurrency
2. **Use connection pooling** for database connections
3. **Implement idempotency** for retry safety
4. **Set appropriate timeouts** and memory settings
5. **Use dead letter queues** for failed events
6. **Implement circuit breakers** for external calls
7. **Monitor with X-Ray** for distributed tracing
Google Antigravity optimizes serverless function code and provides intelligent suggestions for cost and performance improvements.This serverless prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their serverless implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For serverless projects, consider mentioning your framework version, coding style, and any specific libraries you're using.