Design and implement scalable microservices architectures with Google Antigravity
# Microservices Architecture Complete Guide for Google Antigravity
Build scalable, resilient microservices architectures using proven patterns optimized for Google Antigravity IDE development.
## Service Definition
```typescript
// services/user-service/src/index.ts
import Fastify from "fastify";
import { fastifySwagger } from "@fastify/swagger";
import { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
import { userRoutes } from "./routes/users";
import { healthRoutes } from "./routes/health";
import { setupTracing } from "./lib/tracing";
import { setupMetrics } from "./lib/metrics";
const buildServer = async () => {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || "info",
transport: { target: "pino-pretty" }
}
}).withTypeProvider<TypeBoxTypeProvider>();
// Setup observability
await setupTracing(app);
await setupMetrics(app);
// Register plugins
await app.register(fastifySwagger, {
openapi: {
info: { title: "User Service", version: "1.0.0" },
servers: [{ url: process.env.SERVICE_URL }]
}
});
// Register routes
await app.register(healthRoutes, { prefix: "/health" });
await app.register(userRoutes, { prefix: "/api/v1/users" });
return app;
};
const start = async () => {
const app = await buildServer();
const port = parseInt(process.env.PORT || "3000");
await app.listen({ port, host: "0.0.0.0" });
console.log(`User service running on port ${port}`);
};
start().catch(console.error);
```
## Service Communication
```typescript
// lib/service-client.ts
import { createClient } from "@connectrpc/connect";
import { createGrpcTransport } from "@connectrpc/connect-node";
import { UserService } from "./gen/user/v1/user_connect";
import { CircuitBreaker } from "./circuit-breaker";
const circuitBreaker = new CircuitBreaker({
failureThreshold: 5,
resetTimeout: 30000,
halfOpenRequests: 3
});
export const createUserServiceClient = (baseUrl: string) => {
const transport = createGrpcTransport({
baseUrl,
httpVersion: "2",
interceptors: [
(next) => async (req) => {
return circuitBreaker.execute(() => next(req));
}
]
});
return createClient(UserService, transport);
};
// Event-driven communication
import { Kafka, Producer, Consumer } from "kafkajs";
export class EventBus {
private kafka: Kafka;
private producer: Producer;
private consumers: Map<string, Consumer> = new Map();
constructor(brokers: string[]) {
this.kafka = new Kafka({ clientId: "user-service", brokers });
this.producer = this.kafka.producer();
}
async publish<T>(topic: string, event: T): Promise<void> {
await this.producer.send({
topic,
messages: [{ value: JSON.stringify(event), timestamp: Date.now().toString() }]
});
}
async subscribe<T>(topic: string, handler: (event: T) => Promise<void>): Promise<void> {
const consumer = this.kafka.consumer({ groupId: `${topic}-consumer` });
await consumer.connect();
await consumer.subscribe({ topic, fromBeginning: false });
await consumer.run({
eachMessage: async ({ message }) => {
const event = JSON.parse(message.value?.toString() || "{}");
await handler(event);
}
});
this.consumers.set(topic, consumer);
}
}
```
## Saga Pattern Implementation
```typescript
// lib/saga.ts
type SagaStep<T> = {
name: string;
execute: (context: T) => Promise<T>;
compensate: (context: T) => Promise<T>;
};
export class SagaOrchestrator<T> {
private steps: SagaStep<T>[] = [];
private executedSteps: SagaStep<T>[] = [];
addStep(step: SagaStep<T>): this {
this.steps.push(step);
return this;
}
async execute(initialContext: T): Promise<T> {
let context = initialContext;
for (const step of this.steps) {
try {
context = await step.execute(context);
this.executedSteps.push(step);
} catch (error) {
await this.rollback(context);
throw new SagaError(`Step ${step.name} failed`, error);
}
}
return context;
}
private async rollback(context: T): Promise<void> {
for (const step of [...this.executedSteps].reverse()) {
try {
await step.compensate(context);
} catch (compensateError) {
console.error(`Compensation failed for ${step.name}:`, compensateError);
}
}
}
}
```
## Best Practices
1. **Single responsibility** per service with clear boundaries
2. **API versioning** for backward compatibility
3. **Circuit breakers** for fault tolerance
4. **Saga pattern** for distributed transactions
5. **Event sourcing** for audit trails and replay
6. **Service mesh** for traffic management
7. **Centralized logging** and distributed tracing
Google Antigravity provides intelligent assistance for designing service boundaries and implementing communication patterns effectively.This microservices 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 microservices 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 microservices projects, consider mentioning your framework version, coding style, and any specific libraries you're using.