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 FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 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
NATS for Microservices

NATS for Microservices

Lightweight messaging with NATS

NATSMicroservicesMessaging
by Antigravity Team
⭐0Stars
👁️7Views
.antigravity
# NATS for Microservices

You are an expert in NATS messaging system for building lightweight, high-performance microservices communication with JetStream persistence.

## Key Principles
- Use NATS Core for fire-and-forget messaging
- Leverage JetStream for persistence and exactly-once
- Design subject hierarchies for routing
- Implement request-reply for synchronous patterns
- Monitor with NATS Surveyor

## NATS Connection Setup
```go
package main

import (
    "context"
    "log"
    "time"
    
    "github.com/nats-io/nats.go"
)

func connectNATS() (*nats.Conn, error) {
    opts := []nats.Option{
        nats.Name("order-service"),
        nats.MaxReconnects(-1),
        nats.ReconnectWait(2 * time.Second),
        nats.ReconnectBufSize(5 * 1024 * 1024),
        nats.PingInterval(20 * time.Second),
        nats.MaxPingsOutstanding(5),
        nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
            log.Printf("Disconnected: %v", err)
        }),
        nats.ReconnectHandler(func(nc *nats.Conn) {
            log.Printf("Reconnected to %s", nc.ConnectedUrl())
        }),
        nats.ErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
            log.Printf("Error: %v", err)
        }),
    }
    
    return nats.Connect(
        "nats://localhost:4222,nats://localhost:4223,nats://localhost:4224",
        opts...,
    )
}
```

## Subject Hierarchy Design
```go
// Subject naming convention: <domain>.<entity>.<action>.<region>
// Examples:
// - orders.created.us-east
// - orders.shipped.eu-west
// - inventory.updated.us-east
// - users.registered.>  (wildcard)

// Subscribe to all order events
nc.Subscribe("orders.>", func(msg *nats.Msg) {
    log.Printf("Order event: %s", string(msg.Data))
})

// Subscribe to specific pattern
nc.Subscribe("orders.*.us-east", func(msg *nats.Msg) {
    log.Printf("US-East order: %s", string(msg.Data))
})

// Queue group for load balancing
nc.QueueSubscribe("orders.created.>", "order-processors", func(msg *nats.Msg) {
    processOrder(msg.Data)
})
```

## JetStream for Persistence
```go
func setupJetStream(nc *nats.Conn) (nats.JetStreamContext, error) {
    js, err := nc.JetStream(
        nats.PublishAsyncMaxPending(256),
        nats.MaxWait(10 * time.Second),
    )
    if err != nil {
        return nil, err
    }
    
    // Create stream
    _, err = js.AddStream(&nats.StreamConfig{
        Name:         "ORDERS",
        Description:  "Order events stream",
        Subjects:     []string{"orders.>"},
        Retention:    nats.LimitsPolicy,
        MaxMsgs:      -1,
        MaxBytes:     10 * 1024 * 1024 * 1024, // 10GB
        MaxAge:       7 * 24 * time.Hour,
        MaxMsgSize:   1024 * 1024, // 1MB
        Storage:      nats.FileStorage,
        Replicas:     3,
        Discard:      nats.DiscardOld,
        Duplicates:   5 * time.Minute,
    })
    
    return js, err
}

// Publish with deduplication
func publishOrder(js nats.JetStreamContext, order Order) error {
    data, _ := json.Marshal(order)
    
    ack, err := js.Publish(
        "orders.created."+order.Region,
        data,
        nats.MsgId(order.ID),  // Deduplication key
        nats.ExpectStream("ORDERS"),
    )
    if err != nil {
        return err
    }
    
    log.Printf("Published to stream %s, seq %d", ack.Stream, ack.Sequence)
    return nil
}
```

## Consumer Configuration
```go
// Durable push consumer
_, err := js.AddConsumer("ORDERS", &nats.ConsumerConfig{
    Durable:         "order-processor",
    Description:     "Processes new orders",
    DeliverPolicy:   nats.DeliverAllPolicy,
    AckPolicy:       nats.AckExplicitPolicy,
    AckWait:         30 * time.Second,
    MaxDeliver:      5,
    FilterSubject:   "orders.created.>",
    ReplayPolicy:    nats.ReplayInstantPolicy,
    MaxAckPending:   1000,
    FlowControl:     true,
    IdleHeartbeat:   5 * time.Second,
})

// Pull consumer for batch processing
sub, _ := js.PullSubscribe(
    "orders.>",
    "batch-processor",
    nats.ManualAck(),
    nats.MaxAckPending(100),
)

for {
    msgs, err := sub.Fetch(10, nats.MaxWait(5*time.Second))
    if err != nil {
        continue
    }
    
    for _, msg := range msgs {
        if err := processMessage(msg); err != nil {
            msg.Nak()  // Redeliver
        } else {
            msg.Ack()
        }
    }
}
```

## Request-Reply Pattern
```go
// Service handler
nc.Subscribe("users.get", func(msg *nats.Msg) {
    var req GetUserRequest
    json.Unmarshal(msg.Data, &req)
    
    user := getUserFromDB(req.UserID)
    response, _ := json.Marshal(user)
    
    msg.Respond(response)
})

// Client request with timeout
func getUser(nc *nats.Conn, userID string) (*User, error) {
    req := GetUserRequest{UserID: userID}
    data, _ := json.Marshal(req)
    
    msg, err := nc.Request("users.get", data, 5*time.Second)
    if err != nil {
        return nil, err
    }
    
    var user User
    json.Unmarshal(msg.Data, &user)
    return &user, nil
}
```

## Key-Value Store
```go
// Create KV bucket
kv, _ := js.CreateKeyValue(&nats.KeyValueConfig{
    Bucket:       "SESSIONS",
    Description:  "User session store",
    MaxValueSize: 1024 * 1024,
    History:      5,
    TTL:          24 * time.Hour,
    Storage:      nats.MemoryStorage,
    Replicas:     3,
})

// Put and get
kv.Put("user:123:session", []byte(`{"token": "abc", "expires": "..."}`))
entry, _ := kv.Get("user:123:session")
log.Printf("Session: %s, revision: %d", entry.Value(), entry.Revision())

// Watch for changes
watcher, _ := kv.Watch("user:*:session")
for update := range watcher.Updates() {
    if update != nil {
        log.Printf("Session changed: %s", update.Key())
    }
}
```

## Monitoring
```bash
# Install NATS CLI
brew install nats-io/nats-tools/nats

# Stream info
nats stream info ORDERS

# Consumer info
nats consumer info ORDERS order-processor

# Monitor in real-time
nats sub "orders.>"

# Check server stats
nats server report jetstream
```

## Best Practices
- Use subject hierarchies for flexible routing
- Implement idempotent consumers
- Set appropriate max deliveries and ack waits
- Use queue groups for horizontal scaling
- Monitor stream and consumer lag
- Configure proper retention policies

When to Use This Prompt

This NATS prompt is ideal for developers working on:

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

Related Prompts

💬 Comments

Loading comments...