Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Upstash Redis Edge Patterns

Upstash Redis Edge Patterns

Implement serverless Redis with Upstash for caching and rate limiting in Google Antigravity

UpstashRedisCachingRate LimitingServerless
by Antigravity Team
⭐0Stars
.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.

When to Use This Prompt

This Upstash prompt is ideal for developers working on:

  • Upstash applications requiring modern best practices and optimal performance
  • Projects that need production-ready Upstash code with proper error handling
  • Teams looking to standardize their upstash development workflow
  • Developers wanting to learn industry-standard Upstash patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Upstash code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Upstash prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...