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
Background Job Processing

Background Job Processing

Implement reliable background jobs in Google Antigravity with Redis queues and retry logic.

background-jobsqueuesredisworkers
by antigravity-team
⭐0Stars
.antigravity
# Background Jobs for Google Antigravity

Implement reliable background job processing with Redis queues.

## Job Queue

```typescript
// lib/queue/job-queue.ts
import Redis from "ioredis";
import { v4 as uuidv4 } from "uuid";

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

export interface Job<T = unknown> {
    id: string;
    type: string;
    data: T;
    attempts: number;
    maxAttempts: number;
    createdAt: number;
}

export class JobQueue {
    constructor(private name: string) {}

    async add<T>(type: string, data: T, options?: { delay?: number; maxAttempts?: number }): Promise<string> {
        const job: Job<T> = { id: uuidv4(), type, data, attempts: 0, maxAttempts: options?.maxAttempts || 3, createdAt: Date.now() };
        if (options?.delay) {
            await redis.zadd(`queue:${this.name}:delayed`, Date.now() + options.delay, JSON.stringify(job));
        } else {
            await redis.lpush(`queue:${this.name}`, JSON.stringify(job));
        }
        return job.id;
    }

    async process<T>(handler: (job: Job<T>) => Promise<void>): Promise<void> {
        while (true) {
            await this.moveDelayedJobs();
            const jobData = await redis.brpoplpush(`queue:${this.name}`, `queue:${this.name}:processing`, 5);
            if (!jobData) continue;

            const job = JSON.parse(jobData) as Job<T>;
            job.attempts++;

            try {
                await handler(job);
                await redis.lrem(`queue:${this.name}:processing`, 1, jobData);
                console.log(`Job ${job.id} completed`);
            } catch (error) {
                if (job.attempts >= job.maxAttempts) {
                    await redis.lrem(`queue:${this.name}:processing`, 1, jobData);
                    await redis.lpush(`queue:${this.name}:failed`, JSON.stringify(job));
                } else {
                    const delay = Math.pow(2, job.attempts) * 1000;
                    await redis.lrem(`queue:${this.name}:processing`, 1, jobData);
                    await redis.zadd(`queue:${this.name}:delayed`, Date.now() + delay, JSON.stringify(job));
                }
            }
        }
    }

    private async moveDelayedJobs(): Promise<void> {
        const jobs = await redis.zrangebyscore(`queue:${this.name}:delayed`, 0, Date.now());
        for (const job of jobs) {
            await redis.zrem(`queue:${this.name}:delayed`, job);
            await redis.lpush(`queue:${this.name}`, job);
        }
    }

    async getStats(): Promise<{ pending: number; processing: number; failed: number }> {
        const [pending, processing, failed] = await Promise.all([
            redis.llen(`queue:${this.name}`),
            redis.llen(`queue:${this.name}:processing`),
            redis.llen(`queue:${this.name}:failed`),
        ]);
        return { pending, processing, failed };
    }
}
```

## Job Handlers

```typescript
// lib/queue/handlers.ts
import { Job } from "./job-queue";
import { sendEmail } from "@/lib/email";

export const handlers: Record<string, (job: Job<any>) => Promise<void>> = {
    "email.send": async (job) => {
        await sendEmail(job.data);
    },
    "webhook.deliver": async (job) => {
        const { url, payload } = job.data;
        const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
        if (!response.ok) throw new Error(`Failed: ${response.status}`);
    },
};
```

## Worker

```typescript
// scripts/worker.ts
import { JobQueue } from "@/lib/queue/job-queue";
import { handlers } from "@/lib/queue/handlers";

const queue = new JobQueue("default");
console.log("Worker started...");

queue.process(async (job) => {
    const handler = handlers[job.type];
    if (!handler) throw new Error(`Unknown job: ${job.type}`);
    await handler(job);
});
```

## API Route

```typescript
// app/api/jobs/route.ts
import { NextRequest, NextResponse } from "next/server";
import { JobQueue } from "@/lib/queue/job-queue";

const queue = new JobQueue("default");

export async function POST(request: NextRequest) {
    const { type, data, delay } = await request.json();
    const jobId = await queue.add(type, data, { delay });
    return NextResponse.json({ jobId });
}

export async function GET() {
    const stats = await queue.getStats();
    return NextResponse.json(stats);
}
```

## Best Practices

1. **Idempotency**: Design jobs to be safely re-run
2. **Timeouts**: Set appropriate timeouts
3. **Monitoring**: Track success/failure rates
4. **Dead Letter Queue**: Handle permanent failures
5. **Graceful Shutdown**: Handle signals properly

When to Use This Prompt

This background-jobs prompt is ideal for developers working on:

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

Related Prompts

💬 Comments

Loading comments...