Neon Serverless PostgreSQL

Scale-to-zero PostgreSQL with automatic branching and instant provisioning

Neon provides serverless PostgreSQL with automatic scaling, branching, and point-in-time recovery for your AI agents.

python
from praisonaiagents import Agent, MemoryConfig

agent = Agent(
    name="Neon Agent",
    instructions="You are a helpful assistant with persistent memory.",
    memory=MemoryConfig(
        db={"database_url": "postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require"},
    ))
agent.start("Remember that I work at TechCorp as a developer")

The user chats with an agent; Neon wakes on demand, stores session state, and scales to zero when idle.

Diagram

Neon Serverless Flow

Yes

No

🤖 Agent

📝 SQL Request

💤 Sleeping?

⚡ Auto-Wake

🚀 Execute

💾 Durable Storage

😴 Auto-Sleep 5min

How It Works

Diagram
Neon Serverless PostgreSQLAgentUserNeon Serverless PostgreSQLAgentUserRequestProcess requestResult Agent–>>User: Response

Quick Start

  1. Get Neon Credentials
    1. Create account at neon.tech
    2. Create a new project
    3. Copy connection string from dashboard
    bash
    export NEON_DATABASE_URL="postgresql://user:password@ep-xxx.neon.tech/neondb?sslmode=require"
  2. Create Agent with Neon
    python
    from praisonaiagents import Agent, MemoryConfig
    
    agent = Agent(
        name="Neon Agent",
        instructions="You are a helpful assistant with persistent memory.",
        memory=MemoryConfig(
            db={"database_url": "postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require"},
        ))
    
    # Start conversation
    result = agent.start("Remember that I work at TechCorp as a developer")
    print(result)
  3. Test Persistence
    python
    # Later session - agent remembers previous conversation
    result = agent.start("What company do I work for?")
    print(result)  # "You work at TechCorp as a developer"

Installation

pip

bash
# Install with Neon/PostgreSQL support
pip install "praisonai[neon]"

Environment Variables

bash
# Required
export NEON_DATABASE_URL="postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require"

# Optional
export OPENAI_API_KEY="sk-..."  # Or your preferred LLM provider

Configuration Options

OptionTypeDefaultDescription
database_urlstrNoneFull PostgreSQL connection URL
max_retriesint3Retries for cold-start recovery
retry_delayfloat0.5Base delay between retries (seconds)
pool_sizeint5Connection pool size
auto_create_tablesboolTrueCreate conversation tables automatically

Usage Patterns

Using Convenience Class

python
from praisonai.db.adapter import NeonDB
from praisonaiagents import Agent, MemoryConfig

# Auto-reads from NEON_DATABASE_URL environment variable
db = NeonDB()
agent = Agent(name="Neon Agent", memory={"db": db})

Manual Configuration

python
from praisonai.db.adapter import PraisonAIDB
from praisonaiagents import Agent, MemoryConfig

db = PraisonAIDB(
    database_url="postgresql://user:pass@ep-xxx.neon.tech/mydb?sslmode=require",
    max_retries=5,  # Extra retries for cold starts
    retry_delay=1.0  # 1 second base delay
)

agent = Agent(name="Custom Neon Agent", memory={"db": db})

Full Lifecycle Example

python
import os
from praisonai import ManagedAgent, LocalManagedConfig
from praisonai.db.adapter import NeonDB
from praisonaiagents import Agent, MemoryConfig

# Phase 1: Create persistent agent
db = NeonDB(database_url=os.environ["NEON_DATABASE_URL"])
managed = ManagedAgent(
    provider="local",
    db=db,
    config=LocalManagedConfig(
        model="gpt-4o-mini",
        name="Neon Demo Agent",
        system="You are a helpful assistant. Remember all user preferences."
    )
)

agent = Agent(name="User", backend=managed)

# Teach the agent some facts
result1 = agent.run("I prefer concise responses and work in AI/ML")
print(f"Agent: {result1}")

result2 = agent.run("Also, I use Python and prefer practical examples")
print(f"Agent: {result2}")

# Phase 2: Save session and simulate scale-to-zero
session_data = managed.save_ids()
print(f"Session saved: {session_data['session_id']}")
del agent, managed, db  # Simulate shutdown

# Phase 3: Resume from Neon after cold start
db2 = NeonDB(database_url=os.environ["NEON_DATABASE_URL"])
managed2 = ManagedAgent(provider="local", db=db2)
managed2.resume_session(session_data["session_id"])

agent2 = Agent(name="User", backend=managed2)
result3 = agent2.run("What do you know about my preferences?")
print(f"Resumed Agent: {result3}")
# Should recall: concise responses, AI/ML work, Python preference

Neon-Specific Features

Database Branching

Create development branches of your agent’s data:

bash
# Create a branch for testing
neon branches create --name agent-testing --parent main

# Get branch connection string
neon connection-string agent-testing
python
# Use branch for development
dev_db = NeonDB(database_url="postgresql://...@ep-xxx-branch.neon.tech/db")
dev_agent = Agent(name="Dev Agent", memory={"db": dev_db})

# Test new conversation flows without affecting production
result = dev_agent.start("Test new features here")

Point-in-Time Recovery

Restore agent conversations to any point in time:

bash
# Restore database to 2 hours ago
neon branches create --name agent-restore --parent main --point-in-time "2024-01-15 14:00:00"

Connection Pooling

Neon automatically pools connections, but you can tune for your workload:

python
from praisonai.db.adapter import NeonDB

db = NeonDB(
    database_url="postgresql://...?sslmode=require",
    pool_size=10,  # Larger pool for high-concurrency agents
    max_retries=3,  # Standard retry for Neon cold starts
)

Best Practices

Optimize for Cold Starts

Neon databases auto-suspend after 5 minutes of inactivity. The first connection takes ~500ms-2s:

python
from praisonai.db.adapter import NeonDB

# Optimize retry settings for cold starts
db = NeonDB(
    database_url="postgresql://...",
    max_retries=5,  # Extra retries for wake-up
    retry_delay=1.0,  # 1 second between retries
)
Use SSL Connections

Neon requires SSL for all connections. PraisonAI auto-adds sslmode=require:

python
# Both are equivalent - SSL is enforced automatically
db1 = NeonDB(database_url="postgresql://user:pass@ep-xxx.neon.tech/db")
db2 = NeonDB(database_url="postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require")
Monitor Usage

Track your database usage in the Neon dashboard:

  • Compute time: Billed per second of activity
  • Storage: Grows with conversation history
  • Data transfer: Minimal for typical agent workloads

Set up alerts before hitting free tier limits (0.5GB storage, 100 hours compute/month).

Handle Network Issues

PraisonAI automatically handles transient connection failures:

python
# Connection failures are retried automatically
# No manual error handling needed
agent = Agent(
    name="Robust Agent",
    instructions="You handle network issues gracefully.",
    memory=MemoryConfig(
        db={"database_url": os.environ["NEON_DATABASE_URL"]},
    ))

Environment Variables

VariableRequiredFormatExample
NEON_DATABASE_URL✅postgresql://user:pass@host/dbpostgresql://user:pass@ep-xxx.neon.tech/neondb?sslmode=require
OPENAI_API_KEY✅sk-...sk-1234567890abcdef...

Troubleshooting

Cold Start Timeouts

If you see connection timeouts on first request:

python
# Increase retry settings
db = NeonDB(max_retries=5, retry_delay=2.0)

SSL Certificate Issues

Ensure your Neon URL includes SSL mode:

bash
# Add sslmode if missing
export NEON_DATABASE_URL="postgresql://user:pass@ep-xxx.neon.tech/db?sslmode=require"

Connection Pool Exhaustion

For high-concurrency agents, increase pool size:

python
db = NeonDB(pool_size=20)  # Default is 5

Related