NEWn1n v2.0.1 is live! Enterprise Unified LLM API Gateway with 500+ AI Models, up to 90% off,Try now

How to Connect a LangGraph AI Agent to PostgreSQL for Persistent Memory

Authors
  • avatar
    Name
    Nino
    Occupation
    Senior Tech Editor

Building stateful AI agents requires a robust persistence layer to store conversation history, agent state, and memory across sessions. While LangGraph provides an in-memory MemorySaver for development, production systems demand a durable, scalable database. PostgreSQL is the industry standard for this task, offering excellent reliability, transactional safety, and vector extension support (via pgvector).

In this tutorial, we will walk through connecting a LangGraph AI agent to a PostgreSQL database. We will cover setting up Postgres locally using Docker, configuring it in the cloud, implementing connection pooling, and writing the Python code to manage agent state. To power our agent's cognitive capabilities, we will route our LLM requests through n1n.ai, a high-performance LLM API aggregator that provides access to leading models like Claude 3.5 Sonnet and DeepSeek-V3 with unified API keys and optimized routing.


Why PostgreSQL for LangGraph State Management?

LangGraph uses a "checkpointer" pattern to save the state of the agent graph at every step. This enables features like:

  • Thread-safe conversations: Multiple users can interact with the agent simultaneously without state collision.
  • Time travel: Rewinding the agent state to a previous step to debug or allow user corrections.
  • Resilience: Resuming agent execution from the exact point of failure if an API call or server crashes.

While SQLite is convenient for local scripts, PostgreSQL is the preferred choice for enterprise deployment due to its support for concurrent write operations, row-level locking, and robust connection pooling.


System Architecture

The architecture of our stateful agent system consists of three main components:

  1. The Application Layer: A Python application running LangGraph to manage the agent's workflow logic.
  2. The LLM Gateway: n1n.ai, which handles API requests to LLMs (like Claude or GPT-4o) with low latency and automatic failover.
  3. The Persistence Layer: A PostgreSQL database (running locally via Docker or in the cloud via Supabase/RDS) storing agent checkpoints.
+-------------------------------------------------------------+
|                     Python Application                      |
|                                                             |
|   +------------------+             +--------------------+   |
|   |  LangGraph Agent |             |   PostgresSaver    |   |
|   +--------+---------+             +---------+----------+   |
+------------|---------------------------------|--------------+
             |                                 |
             | (LLM API Calls)                 | (State Checkpoints)
             v                                 v
+----------------------------+     +--------------------------+
|      n1n.ai Gateway        |     |   PostgreSQL Database    |
|  (Claude / DeepSeek-V3)    |     |   (Docker / Cloud RDS)   |
+----------------------------+     +--------------------------+

Step 1: Setting Up PostgreSQL

Option A: Local Setup via Docker Compose

For local development, Docker Compose is the cleanest way to spin up a PostgreSQL instance. Create a docker-compose.yml file in your project root:

version: '3.8'

services:
  postgres:
    image: postgres:16-alpine
    container_name: langgraph_postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: langgraph_db
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Start the database by running:

docker compose up -d

Option B: Cloud Deployment

For production, you can use managed Postgres services like Supabase, Neon, or AWS RDS. Ensure you obtain the connection string (URI) formatted as follows:

postgresql://username:password@hostname:port/database_name?sslmode=require

Step 2: Project Setup and Dependencies

Create a virtual environment and install the required dependencies. We need langgraph, the PostgreSQL checkpointer implementation (langgraph-checkpoint-postgres), and psycopg for connection pooling.

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install langgraph langgraph-checkpoint-postgres psycopg[binary,pool] langchain-openai python-dotenv

Next, create a .env file to store your credentials. We will use n1n.ai to route our LLM requests. Set the OPENAI_API_BASE to route through the aggregator:

N1N_API_KEY=your_n1n_api_key_here
DATABASE_URL=postgresql://postgres:mysecretpassword@localhost:5432/langgraph_db

Step 3: Implementing the LangGraph Agent with PostgresSaver

Now, let's write the Python implementation. We will use the modern psycopg connection pool to manage database connections efficiently. Using a connection pool is crucial for web applications and API servers where multiple threads concurrently access the database.

Create a file named agent.py:

import os
from typing import Annotated, TypedDict
from dotenv import load_dotenv
from psycopg_pool import ConnectionPool

from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.checkpoint.postgres import PostgresSaver
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_openai import ChatOpenAI

load_dotenv()

# Define the state schema
class AgentState(TypedDict):
    messages: Annotated[list[BaseMessage], add_messages]

# Initialize the LLM client pointing to the n1n.ai gateway
# This allows us to use top-tier models with optimized latency
llm = ChatOpenAI(
    model="deepseek-ai/DeepSeek-V3", # Or "anthropic/claude-3.5-sonnet"
    api_key=os.getenv("N1N_API_KEY"),
    base_url="https://api.n1n.ai/v1"
)

# Define a simple node that calls the LLM
def call_model(state: AgentState):
    response = llm.invoke(state["messages"])
    return {"messages": [response]}

# Set up the state graph workflow
workflow = StateGraph(AgentState)
workflow.add_node("agent", call_model)
workflow.add_edge(START, "agent")
workflow.add_edge("agent", END)

# Define connection parameters
DB_URI = os.getenv("DATABASE_URL")

def run_agent():
    # Establish a connection pool to PostgreSQL
    with ConnectionPool(conninfo=DB_URI, max_size=10) as pool:
        # Initialize the Postgres checkpointer
        checkpointer = PostgresSaver(pool)
        
        # Create the tables if they don't exist yet
        checkpointer.setup()
        
        # Compile the graph with persistence enabled
        app = workflow.compile(checkpointer=checkpointer)
        
        # Configure a thread ID to track the conversation session
        config = {"configurable": {"thread_id": "session_abc_123"}}
        
        # First turn
        print("--- First Turn ---")
        user_message = HumanMessage(content="Hi, my name is Alice. Remember my name!")
        events = app.stream({"messages": [user_message]}, config, stream_mode="values")
        for event in events:
            event["messages"][-1].pretty_print()
            
        # Second turn (verifying memory persistence)
        print("\n--- Second Turn ---")
        follow_up = HumanMessage(content="What is my name?")
        events = app.stream({"messages": [follow_up]}, config, stream_mode="values")
        for event in events:
            event["messages"][-1].pretty_print()

if __name__ == "__main__":
    run_agent()

Step 4: Deep Dive into the Database Tables

When you call checkpointer.setup(), LangGraph automatically creates the necessary tables in your PostgreSQL database. Let's inspect what is created under the hood.

Connect to your database using psql or a GUI tool like DBeaver:

docker exec -it langgraph_postgres psql -U postgres -d langgraph_db

Run \dt to list the tables. You will see:

Table NameDescription
checkpointsStores the serialized state representation of the graph at each step.
checkpoint_writesStores intermediate writes and channel updates before they are committed.
checkpoint_blobsStores binary large objects (BLOBs) containing serialized data payload.
checkpoint_writesTracks metadata and side-effects of node executions.

This schema ensures that if your agent encounters an error mid-execution, the exact state of the graph can be recovered from the last successful checkpoint. This level of transactional safety is what makes Postgres ideal for production-grade AI agents.


Advanced Production Patterns

1. Connection Pooling in Serverless Environments

If you are deploying your Python application to serverless platforms (like AWS Lambda or Vercel Functions), persistent connection pools can exhaust database connections quickly because serverless instances scale horizontally. In such scenarios:

  • Use a connection pooler like PgBouncer in front of your PostgreSQL database.
  • Set min_size=1 and max_size=2 in your ConnectionPool config to prevent connection exhaustion.
  • Ensure you close connections properly during the function teardown phase.

2. Schema Migrations

When upgrading LangGraph or modifying your agent's state schema, you must manage database migrations carefully. PostgresSaver handles internal checkpoint schemas automatically, but if you store custom application data in parallel tables, use tools like Alembic to coordinate schema upgrades without causing downtime.

3. High-Concurrency LLM Routing

In high-throughput environments, database latency and LLM API response times are your primary bottlenecks. By utilizing n1n.ai, you ensure that your LLM API calls are routed through the fastest available nodes. Combining this with a database hosted in the same cloud region minimizes latency to sub-millisecond levels, providing a seamless user experience.


Conclusion

Transitioning from in-memory state management to PostgreSQL is a critical milestone when moving a LangGraph agent from prototype to production. By using the PostgresSaver alongside a robust connection pool, you ensure your agent's memory is durable, secure, and ready to scale.

For developers looking to optimize their LLM costs and performance while building stateful agents, routing traffic through n1n.ai offers unmatched stability and access to the latest frontier models.

Get a free API key at n1n.ai