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
API Rate Limiting with Redis

API Rate Limiting with Redis

Implement API rate limiting in Google Antigravity with Redis and sliding window algorithms.

rate-limitingredisapisecurity
by antigravity-team
⭐0Stars
.antigravity
# API Rate Limiting for Google Antigravity

Protect your APIs from abuse with effective rate limiting using Redis.

## Redis Rate Limiter

```typescript
// lib/rate-limiter.ts
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

interface RateLimitResult {
    success: boolean;
    remaining: number;
    reset: number;
}

export async function checkRateLimit(key: string, limit: number, windowSeconds: number): Promise<RateLimitResult> {
    const now = Date.now();
    const windowStart = now - windowSeconds * 1000;
    const redisKey = `ratelimit:${key}`;

    const pipeline = redis.pipeline();
    pipeline.zremrangebyscore(redisKey, 0, windowStart);
    pipeline.zadd(redisKey, now, `${now}-${Math.random()}`);
    pipeline.zcard(redisKey);
    pipeline.expire(redisKey, windowSeconds);

    const results = await pipeline.exec();
    const count = results?.[2]?.[1] as number;

    return {
        success: count <= limit,
        remaining: Math.max(0, limit - count),
        reset: Math.ceil((windowStart + windowSeconds * 1000) / 1000),
    };
}
```

## Token Bucket

```typescript
// lib/token-bucket.ts
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

export async function consumeToken(key: string, config: { maxTokens: number; refillRate: number; refillInterval: number }): Promise<{ allowed: boolean; tokens: number }> {
    const script = `
        local tokens = tonumber(redis.call("get", KEYS[1]) or ARGV[1])
        local lastRefill = tonumber(redis.call("get", KEYS[2]) or ARGV[4])
        local now = tonumber(ARGV[4])
        local elapsed = now - lastRefill
        local refills = math.floor(elapsed / tonumber(ARGV[3]))
        tokens = math.min(tonumber(ARGV[1]), tokens + refills * tonumber(ARGV[2]))
        if tokens >= 1 then
            tokens = tokens - 1
            redis.call("set", KEYS[1], tokens)
            redis.call("set", KEYS[2], now)
            return {1, tokens}
        end
        return {0, tokens}
    `;
    const result = await redis.eval(script, 2, `bucket:${key}:tokens`, `bucket:${key}:lastRefill`, config.maxTokens, config.refillRate, config.refillInterval, Date.now()) as [number, number];
    return { allowed: result[0] === 1, tokens: result[1] };
}
```

## Middleware

```typescript
// middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { checkRateLimit } from "@/lib/rate-limiter";

export async function middleware(request: NextRequest) {
    if (request.nextUrl.pathname.startsWith("/api")) {
        const ip = request.ip || "unknown";
        const { success, remaining, reset } = await checkRateLimit(`${ip}:${request.nextUrl.pathname}`, 100, 60);

        if (!success) {
            return new NextResponse(JSON.stringify({ error: "Too many requests" }), {
                status: 429,
                headers: { "X-RateLimit-Remaining": "0", "Retry-After": "60" },
            });
        }

        const response = NextResponse.next();
        response.headers.set("X-RateLimit-Remaining", remaining.toString());
        return response;
    }
    return NextResponse.next();
}
```

## In-Memory Limiter

```typescript
// lib/memory-rate-limiter.ts
const counts = new Map<string, { count: number; resetAt: number }>();

export function checkMemoryRateLimit(key: string, limit: number, windowMs: number): { allowed: boolean; remaining: number } {
    const now = Date.now();
    const record = counts.get(key);
    if (!record || now > record.resetAt) {
        counts.set(key, { count: 1, resetAt: now + windowMs });
        return { allowed: true, remaining: limit - 1 };
    }
    if (record.count >= limit) return { allowed: false, remaining: 0 };
    record.count++;
    return { allowed: true, remaining: limit - record.count };
}

setInterval(() => {
    const now = Date.now();
    for (const [key, record] of counts) if (now > record.resetAt) counts.delete(key);
}, 60000);
```

## Best Practices

1. **Distributed Storage**: Use Redis for rate limiting across instances
2. **Headers**: Always return rate limit headers
3. **Tiered Limits**: Different limits for auth vs anonymous
4. **Burst Handling**: Allow bursts with token bucket
5. **Monitoring**: Log rate limit hits

When to Use This Prompt

This rate-limiting prompt is ideal for developers working on:

  • rate-limiting applications requiring modern best practices and optimal performance
  • Projects that need production-ready rate-limiting code with proper error handling
  • Teams looking to standardize their rate-limiting development workflow
  • Developers wanting to learn industry-standard rate-limiting 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 rate-limiting 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 rate-limiting 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 rate-limiting 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 rate-limiting projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...