Edge-ready database access with Prisma Accelerate for Google Antigravity projects including connection pooling and global caching.
# Prisma Accelerate Edge Caching for Google Antigravity
Deploy database access at the edge with Prisma Accelerate in your Google Antigravity IDE projects. This comprehensive guide covers connection pooling, global caching, and edge runtime patterns optimized for Gemini 3 agentic development.
## Prisma Setup
Configure Prisma with Accelerate extension:
```typescript
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
model Prompt {
id String @id @default(cuid())
slug String @unique
title String
description String
content String
tags String[]
authorId String?
isApproved Boolean @default(false)
viewCount Int @default(0)
starCount Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([isApproved, createdAt])
}
```
## Client Configuration
Set up Prisma Client with Accelerate:
```typescript
// lib/prisma.ts
import { PrismaClient } from '@prisma/client';
import { withAccelerate } from '@prisma/extension-accelerate';
export const prismaEdge = new PrismaClient().$extends(withAccelerate());
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query'] : [],
});
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}
```
## Caching Strategies
Implement different cache strategies:
```typescript
// lib/queries.ts
import { prismaEdge } from './prisma';
// Short TTL for frequently changing data
export async function getPrompts({ page = 1, limit = 20 }) {
const offset = (page - 1) * limit;
const [prompts, total] = await Promise.all([
prismaEdge.prompt.findMany({
where: { isApproved: true },
orderBy: { createdAt: 'desc' },
take: limit,
skip: offset,
cacheStrategy: {
ttl: 60, // 1 minute
swr: 120, // Stale-while-revalidate for 2 minutes
},
}),
prismaEdge.prompt.count({
where: { isApproved: true },
cacheStrategy: { ttl: 60 },
}),
]);
return { prompts, total, page, limit };
}
// Longer TTL for static content
export async function getPromptBySlug(slug: string) {
return prismaEdge.prompt.findUnique({
where: { slug },
cacheStrategy: {
ttl: 300, // 5 minutes
swr: 600, // 10 minutes stale-while-revalidate
tags: [`prompt:${slug}`],
},
});
}
// No cache for user-specific data
export async function getUserPrompts(userId: string) {
return prismaEdge.prompt.findMany({
where: { authorId: userId },
orderBy: { createdAt: 'desc' },
// No cacheStrategy = no caching
});
}
```
## Edge API Routes
Create edge-compatible API routes:
```typescript
// app/api/prompts/route.ts
import { NextRequest } from 'next/server';
import { getPrompts } from '@/lib/queries';
export const runtime = 'edge';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const page = Number(searchParams.get('page')) || 1;
const limit = Number(searchParams.get('limit')) || 20;
try {
const result = await getPrompts({ page, limit });
return Response.json(result, {
headers: {
'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=120',
},
});
} catch (error) {
console.error('Failed to fetch prompts:', error);
return Response.json({ error: 'Failed to fetch prompts' }, { status: 500 });
}
}
```
## Cache Invalidation
Invalidate cache when data changes:
```typescript
// lib/mutations.ts
import { prismaEdge } from './prisma';
export async function createPrompt(data: {
title: string;
description: string;
content: string;
tags: string[];
authorId: string;
}) {
const slug = data.title.toLowerCase().replace(/[^a-z0-9]+/g, '-');
const prompt = await prismaEdge.prompt.create({
data: { ...data, slug },
});
// Invalidate list cache
await prismaEdge.$accelerate.invalidate({
tags: ['prompts:list'],
});
return prompt;
}
export async function updatePrompt(id: string, data: Partial<{
title: string;
description: string;
content: string;
tags: string[];
}>) {
const prompt = await prismaEdge.prompt.update({
where: { id },
data,
});
// Invalidate specific prompt and list caches
await prismaEdge.$accelerate.invalidate({
tags: [`prompt:${prompt.slug}`, 'prompts:list'],
});
return prompt;
}
```
## Best Practices
1. **Use Accelerate extension** for edge runtime compatibility
2. **Configure cache strategies** based on data volatility
3. **Use tags** for targeted cache invalidation
4. **Set appropriate TTL and SWR** values for your use case
5. **Skip caching** for user-specific or sensitive data
6. **Use transactions** for atomic operations
7. **Monitor cache hit rates** with Prisma Data PlatformThis prisma 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 prisma 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 prisma projects, consider mentioning your framework version, coding style, and any specific libraries you're using.