Implement effective caching for optimal performance
# Caching Strategies Complete Guide for Google Antigravity
Implement effective caching strategies for optimal performance with Google Antigravity IDE.
## Next.js Data Caching
```typescript
// app/products/page.tsx
// Static caching - data cached indefinitely
async function getProducts() {
const res = await fetch("https://api.example.com/products", {
cache: "force-cache" // Default behavior
});
return res.json();
}
// Time-based revalidation
async function getProductsRevalidated() {
const res = await fetch("https://api.example.com/products", {
next: { revalidate: 3600 } // Revalidate every hour
});
return res.json();
}
// No caching - always fresh
async function getProductsFresh() {
const res = await fetch("https://api.example.com/products", {
cache: "no-store"
});
return res.json();
}
// Tag-based revalidation
async function getProduct(id: string) {
const res = await fetch(`https://api.example.com/products/${id}`, {
next: { tags: ["products", `product-${id}`] }
});
return res.json();
}
// Revalidate by tag
import { revalidateTag } from "next/cache";
export async function updateProduct(id: string, data: ProductData) {
await db.update(products).set(data).where(eq(products.id, id));
revalidateTag(`product-${id}`);
revalidateTag("products");
}
```
## Redis Caching Layer
```typescript
// lib/cache.ts
import { Redis } from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
interface CacheOptions {
ttl?: number;
tags?: string[];
}
export async function cached<T>(
key: string,
fn: () => Promise<T>,
options: CacheOptions = {}
): Promise<T> {
const { ttl = 3600, tags = [] } = options;
// Try to get from cache
const cached = await redis.get(key);
if (cached) {
return JSON.parse(cached);
}
// Execute function and cache result
const result = await fn();
await redis.setex(key, ttl, JSON.stringify(result));
// Track tags for invalidation
for (const tag of tags) {
await redis.sadd(`tag:${tag}`, key);
}
return result;
}
export async function invalidateTag(tag: string): Promise<void> {
const keys = await redis.smembers(`tag:${tag}`);
if (keys.length > 0) {
await redis.del(...keys);
await redis.del(`tag:${tag}`);
}
}
// Usage
export async function getUser(id: string) {
return cached(
`user:${id}`,
() => db.query.users.findFirst({ where: eq(users.id, id) }),
{ ttl: 600, tags: ["users", `user:${id}`] }
);
}
```
## HTTP Caching Headers
```typescript
// app/api/products/route.ts
import { NextResponse } from "next/server";
export async function GET() {
const products = await getProducts();
return NextResponse.json(products, {
headers: {
"Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400",
"CDN-Cache-Control": "max-age=3600",
"Vercel-CDN-Cache-Control": "max-age=3600"
}
});
}
// next.config.ts
export default {
async headers() {
return [
{
source: "/api/products",
headers: [
{
key: "Cache-Control",
value: "public, s-maxage=3600, stale-while-revalidate=86400"
}
]
}
];
}
};
```
## Best Practices
1. **Cache at multiple layers** (CDN, application, database)
2. **Use appropriate TTLs** based on data freshness needs
3. **Implement cache invalidation** with tags
4. **Consider stale-while-revalidate** for better UX
5. **Monitor cache hit rates** in production
6. **Handle cache misses** gracefully
7. **Use consistent cache keys** across the application
Google Antigravity helps implement efficient caching strategies for optimal performance.This caching 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 caching 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 caching projects, consider mentioning your framework version, coding style, and any specific libraries you're using.