Master Temporal workflow orchestration for Google Antigravity IDE distributed systems
# Temporal Workflow Patterns for Google Antigravity IDE
Build reliable distributed systems with Temporal using Google Antigravity IDE. This comprehensive guide covers workflow design, activities, signals, queries, and saga patterns for complex business processes.
## Workflow Definition
```typescript
// src/workflows/order-processing.ts
import { proxyActivities, sleep, condition, defineSignal, defineQuery, setHandler } from "@temporalio/workflow";
import type * as activities from "../activities";
const {
validateOrder,
reserveInventory,
processPayment,
shipOrder,
sendNotification,
releaseInventory,
refundPayment,
} = proxyActivities<typeof activities>({
startToCloseTimeout: "1 minute",
retry: {
maximumAttempts: 3,
initialInterval: "1 second",
backoffCoefficient: 2,
maximumInterval: "30 seconds",
},
});
// Signals for external events
export const cancelOrderSignal = defineSignal<[string]>("cancelOrder");
export const updateShippingSignal = defineSignal<[ShippingInfo]>("updateShipping");
// Queries for workflow state
export const getOrderStatusQuery = defineQuery<OrderStatus>("getOrderStatus");
interface OrderInput {
orderId: string;
userId: string;
items: OrderItem[];
shippingInfo: ShippingInfo;
}
interface OrderStatus {
stage: "validating" | "reserving" | "processing_payment" | "shipping" | "completed" | "cancelled" | "failed";
timestamp: Date;
error?: string;
}
export async function orderProcessingWorkflow(input: OrderInput): Promise<OrderResult> {
let status: OrderStatus = { stage: "validating", timestamp: new Date() };
let cancelled = false;
let cancellationReason = "";
let shippingInfo = input.shippingInfo;
const compensations: Array<() => Promise<void>> = [];
// Set up signal handlers
setHandler(cancelOrderSignal, (reason: string) => {
cancelled = true;
cancellationReason = reason;
});
setHandler(updateShippingSignal, (newShipping: ShippingInfo) => {
shippingInfo = newShipping;
});
// Set up query handlers
setHandler(getOrderStatusQuery, () => status);
try {
// Stage 1: Validate order
status = { stage: "validating", timestamp: new Date() };
const validation = await validateOrder(input.orderId, input.items);
if (!validation.valid) {
throw new Error(`Validation failed: ${validation.reason}`);
}
// Check for cancellation
if (cancelled) {
throw new CancellationError(cancellationReason);
}
// Stage 2: Reserve inventory
status = { stage: "reserving", timestamp: new Date() };
const reservation = await reserveInventory(input.orderId, input.items);
compensations.push(async () => {
await releaseInventory(input.orderId, reservation.reservationId);
});
if (cancelled) {
throw new CancellationError(cancellationReason);
}
// Stage 3: Process payment
status = { stage: "processing_payment", timestamp: new Date() };
const payment = await processPayment(input.orderId, input.userId, reservation.total);
compensations.push(async () => {
await refundPayment(payment.paymentId);
});
if (cancelled) {
throw new CancellationError(cancellationReason);
}
// Stage 4: Ship order
status = { stage: "shipping", timestamp: new Date() };
const shipment = await shipOrder(input.orderId, shippingInfo);
// Stage 5: Send confirmation
await sendNotification(input.userId, "order_shipped", {
orderId: input.orderId,
trackingNumber: shipment.trackingNumber,
});
status = { stage: "completed", timestamp: new Date() };
return {
success: true,
orderId: input.orderId,
trackingNumber: shipment.trackingNumber,
};
} catch (error) {
// Execute compensations in reverse order (saga pattern)
status = {
stage: cancelled ? "cancelled" : "failed",
timestamp: new Date(),
error: error instanceof Error ? error.message : "Unknown error",
};
for (const compensation of compensations.reverse()) {
try {
await compensation();
} catch (compError) {
console.error("Compensation failed:", compError);
}
}
throw error;
}
}
```
## Activities Implementation
```typescript
// src/activities/index.ts
import { ApplicationFailure } from "@temporalio/activity";
import { db } from "@/lib/db";
import { stripe } from "@/lib/stripe";
import { inventoryService } from "@/services/inventory";
export async function validateOrder(
orderId: string,
items: OrderItem[]
): Promise<{ valid: boolean; reason?: string }> {
// Validate items exist and are available
for (const item of items) {
const product = await db.product.findUnique({
where: { id: item.productId },
});
if (!product) {
return { valid: false, reason: `Product ${item.productId} not found` };
}
if (!product.active) {
return { valid: false, reason: `Product ${product.name} is no longer available` };
}
if (item.quantity > product.maxQuantity) {
return { valid: false, reason: `Quantity exceeds maximum for ${product.name}` };
}
}
return { valid: true };
}
export async function reserveInventory(
orderId: string,
items: OrderItem[]
): Promise<{ reservationId: string; total: number }> {
const reservation = await inventoryService.reserve({
orderId,
items,
expiresIn: 15 * 60 * 1000, // 15 minutes
});
if (!reservation.success) {
throw ApplicationFailure.nonRetryable(
`Inventory reservation failed: ${reservation.reason}`,
"INVENTORY_UNAVAILABLE"
);
}
return {
reservationId: reservation.id,
total: reservation.total,
};
}
export async function processPayment(
orderId: string,
userId: string,
amount: number
): Promise<{ paymentId: string }> {
const user = await db.user.findUnique({ where: { id: userId } });
if (!user?.stripeCustomerId) {
throw ApplicationFailure.nonRetryable(
"User has no payment method",
"NO_PAYMENT_METHOD"
);
}
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(amount * 100),
currency: "usd",
customer: user.stripeCustomerId,
confirm: true,
off_session: true,
metadata: { orderId },
});
return { paymentId: paymentIntent.id };
} catch (error: any) {
if (error.code === "card_declined") {
throw ApplicationFailure.nonRetryable(
"Payment declined",
"PAYMENT_DECLINED"
);
}
throw error;
}
}
```
## Client Usage
```typescript
// src/services/order-client.ts
import { Client, Connection } from "@temporalio/client";
import { orderProcessingWorkflow, cancelOrderSignal, getOrderStatusQuery } from "@/workflows/order-processing";
const connection = await Connection.connect({ address: process.env.TEMPORAL_ADDRESS });
const client = new Client({ connection, namespace: "default" });
export async function startOrder(input: OrderInput) {
const handle = await client.workflow.start(orderProcessingWorkflow, {
taskQueue: "orders",
workflowId: `order-${input.orderId}`,
args: [input],
});
return { workflowId: handle.workflowId };
}
export async function cancelOrder(orderId: string, reason: string) {
const handle = client.workflow.getHandle(`order-${orderId}`);
await handle.signal(cancelOrderSignal, reason);
}
export async function getOrderStatus(orderId: string) {
const handle = client.workflow.getHandle(`order-${orderId}`);
return await handle.query(getOrderStatusQuery);
}
```
## Best Practices for Google Antigravity IDE
When using Temporal with Google Antigravity, design workflows to be deterministic. Use activities for non-deterministic operations. Implement compensation logic for saga patterns. Use signals for external events. Use queries for workflow state. Let Gemini 3 generate workflow definitions from business requirements.
Google Antigravity excels at modeling complex business processes as Temporal workflows.This Temporal 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 temporal 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 Temporal projects, consider mentioning your framework version, coding style, and any specific libraries you're using.