Implement serverless Redis with Upstash for caching and rate limiting in Google Antigravity
# Upstash Redis Edge Patterns for Google Antigravity
Upstash provides serverless Redis for edge environments. This guide covers patterns for Google Antigravity IDE and Gemini 3.
## Redis Client Setup
```typescript
// lib/redis.ts
import { Redis } from '@upstash/redis';
export const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
// Type-safe commands
export async function cacheGet<T>(key: string): Promise<T | null> {
return redis.get<T>(key);
}
export async function cacheSet<T>(key: string, value: T, ttlSeconds?: number): Promise<void> {
if (ttlSeconds) {
await redis.setex(key, ttlSeconds, value);
} else {
await redis.set(key, value);
}
}
export async function cacheDel(key: string): Promise<void> {
await redis.del(key);
}
export async function cacheGetOrSet<T>(
key: string,
fetcher: () => Promise<T>,
ttlSeconds = 3600
): Promise<T> {
const cached = await cacheGet<T>(key);
if (cached !== null) return cached;
const fresh = await fetcher();
await cacheSet(key, fresh, ttlSeconds);
return fresh;
}
```
## Rate Limiting
```typescript
// lib/ratelimit.ts
import { Ratelimit } from '@upstash/ratelimit';
import { redis } from './redis';
// Sliding window rate limiter
export const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds
analytics: true,
prefix: '@upstash/ratelimit',
});
// API route rate limiter
export const apiRatelimit = new Ratelimit({
redis,
limiter: Ratelimit.tokenBucket(100, '1 m', 10), // 100 tokens, refill 10 per minute
});
// Tiered rate limits
export function createTieredRatelimit(tier: 'free' | 'pro' | 'enterprise') {
const limits = {
free: Ratelimit.slidingWindow(10, '1 m'),
pro: Ratelimit.slidingWindow(100, '1 m'),
enterprise: Ratelimit.slidingWindow(1000, '1 m'),
};
return new Ratelimit({
redis,
limiter: limits[tier],
prefix: `ratelimit:${tier}`
});
}
```
## Middleware Rate Limiting
```typescript
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { ratelimit } from './lib/ratelimit';
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/api')) {
const ip = request.ip ?? '127.0.0.1';
const { success, limit, remaining, reset } = await ratelimit.limit(ip);
if (!success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: {
'X-RateLimit-Limit': limit.toString(),
'X-RateLimit-Remaining': remaining.toString(),
'X-RateLimit-Reset': reset.toString(),
},
}
);
}
const response = NextResponse.next();
response.headers.set('X-RateLimit-Limit', limit.toString());
response.headers.set('X-RateLimit-Remaining', remaining.toString());
return response;
}
return NextResponse.next();
}
export const config = {
matcher: '/api/:path*',
};
```
## Session Store
```typescript
// lib/session-store.ts
import { redis } from './redis';
interface Session {
userId: string;
email: string;
role: string;
createdAt: number;
}
const SESSION_TTL = 60 * 60 * 24 * 7; // 7 days
export async function createSession(userId: string, data: Omit<Session, 'userId' | 'createdAt'>): Promise<string> {
const sessionId = crypto.randomUUID();
const session: Session = {
userId,
...data,
createdAt: Date.now(),
};
await redis.setex(`session:${sessionId}`, SESSION_TTL, session);
await redis.sadd(`user:${userId}:sessions`, sessionId);
return sessionId;
}
export async function getSession(sessionId: string): Promise<Session | null> {
return redis.get<Session>(`session:${sessionId}`);
}
export async function deleteSession(sessionId: string): Promise<void> {
const session = await getSession(sessionId);
if (session) {
await redis.del(`session:${sessionId}`);
await redis.srem(`user:${session.userId}:sessions`, sessionId);
}
}
export async function deleteAllUserSessions(userId: string): Promise<void> {
const sessionIds = await redis.smembers<string[]>(`user:${userId}:sessions`);
if (sessionIds.length > 0) {
await redis.del(...sessionIds.map(id => `session:${id}`));
await redis.del(`user:${userId}:sessions`);
}
}
```
## Leaderboard
```typescript
// lib/leaderboard.ts
import { redis } from './redis';
const LEADERBOARD_KEY = 'leaderboard:global';
export async function addScore(userId: string, score: number): Promise<void> {
await redis.zadd(LEADERBOARD_KEY, { score, member: userId });
}
export async function incrementScore(userId: string, amount: number): Promise<number> {
return redis.zincrby(LEADERBOARD_KEY, amount, userId);
}
export async function getTopPlayers(count = 10): Promise<Array<{ userId: string; score: number }>> {
const results = await redis.zrange<string[]>(LEADERBOARD_KEY, 0, count - 1, { rev: true, withScores: true });
const players: Array<{ userId: string; score: number }> = [];
for (let i = 0; i < results.length; i += 2) {
players.push({ userId: results[i], score: parseFloat(results[i + 1]) });
}
return players;
}
export async function getRank(userId: string): Promise<number | null> {
const rank = await redis.zrevrank(LEADERBOARD_KEY, userId);
return rank !== null ? rank + 1 : null;
}
```
## Best Practices
1. **Edge Compatible**: Works in Vercel Edge, Cloudflare Workers
2. **REST API**: HTTP-based, no persistent connections
3. **Rate Limiting**: Built-in sliding window, token bucket
4. **Pipeline**: Batch commands for efficiency
5. **TTL**: Always set expiration on cache keys
6. **Analytics**: Built-in usage analytics
Google Antigravity's Gemini 3 understands Upstash patterns for serverless Redis.This Upstash 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 upstash 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 Upstash projects, consider mentioning your framework version, coding style, and any specific libraries you're using.