Lesson 410 min

Supabase N8N With Postgres Memory

Learn how to build AI agents with persistent memory using Supabase Postgres database and n8n workflows for context-aware conversations

Supabase N8N With Postgres Memory Tutorial

If you're still using simple memories in your AI agents, you're missing out! Simple memories are non-persistent, meaning when you restart your workflow, all conversation history is lost. To retain information across sessions, you need persistent storage.

In this tutorial, you'll learn how to set up Postgres Chat Memory using Supabase and n8n, enabling your AI agents to remember conversations even after workflow restarts.

Why Postgres Chat Memory?

Simple Memory vs Postgres Memory:

  • Simple Memory: Non-persistent, lost on workflow restart
  • Postgres Memory: Persistent storage that retains all conversation history

Benefits:

  • Persistence: Conversations survive restarts and can be accessed across sessions
  • Reliability: Hosted on Supabase, a robust backend platform
  • Scalability: Handle thousands of conversations efficiently
  • Real-time Access: Query and retrieve conversation history anytime

Prerequisites

Before starting, you'll need:

  1. Supabase Account - Sign up at supabase.com
  2. N8N Instance - Self-hosted or cloud instance
  3. AI Agent Workflow - Basic n8n AI agent setup

Step 1: Create Supabase Project

1.1 Set Up New Project

  1. Log in to your Supabase dashboard

  2. Click "New Project"

  3. Enter project details:

    • Name: n8n-supabase-integration (or any name you prefer)
    • Database Password: Generate a strong password

    ⚠️ Important: Copy and save your database password immediately - you won't be able to see it again!

  4. Click "Create New Project"

  5. Wait for the project to finish provisioning (usually takes 1-2 minutes)


Step 2: Configure Postgres Memory in N8N

2.1 Add Postgres Chat Memory Node

  1. Open your n8n workflow
  2. Click on your AI Agent node
  3. In the Memory section, select "Postgres Chat Memory"
  4. Click "Create New Credential" for Postgres

2.2 Get Connection Details from Supabase

Now you need to get your database connection details from Supabase:

  1. Go back to your Supabase project
  2. Navigate to Project Settings (gear icon in sidebar)
  3. Click on "Database" in the left menu
  4. Scroll to the "Connection String" section
  5. Select "Connection Pooling" tab
  6. Choose "Transaction" mode (recommended for multiple concurrent transactions)
  7. Select "PSQL" format

You'll see a connection string that looks like this:

psql -h aws-0-us-west-1.pooler.supabase.com -p 6543 -d postgres -U postgres.xxxxxxxxxxxx

2.3 Parse Connection Details

Let's break down this connection string to fill in the n8n credentials:

Connection String Format:

-h [HOST] -p [PORT] -d [DATABASE] -U [USERNAME]

Extract each value:

  • Host: Everything after -h (e.g., aws-0-us-west-1.pooler.supabase.com)
  • Port: Everything after -p (e.g., 6543)
  • Database: Everything after -d (usually postgres)
  • User: Everything after -U (e.g., postgres.xxxxxxxxxxxx)
  • Password: The password you saved when creating the project

2.4 Fill in N8N Credentials

In the n8n Postgres credential form, enter:

  1. Host: Paste the host from -h
  2. Database: postgres (from -d)
  3. User: Paste the username from -U
  4. Password: Paste the password you saved earlier
  5. Port: Paste the port from -p (usually 6543 for pooled connection)
  6. SSL: Leave as default (usually enabled for Supabase)

Click "Save" to test the connection. You should see a green checkmark if successful!


Step 3: Configure Memory Settings

3.1 Memory Node Configuration

In the Postgres Chat Memory node, configure:

  • Table Name: n8n_chat_histories (default - you can change this)
  • Session ID: Use a unique identifier for each conversation session
  • Context Window Length: Number of messages to retain in memory (e.g., 10)

The context window length determines how many previous messages the AI agent will remember during the conversation.

Context Window Length: 10 = Remembers last 10 messages

Step 4: Test Your Memory Setup

4.1 Run Your First Message

  1. Trigger your workflow with a test message:

    User: "Hi, I want to ask one question"
    
  2. The workflow should execute successfully

  3. The Postgres memory node will automatically create the necessary table in Supabase

4.2 Verify in Supabase

  1. Go back to Supabase
  2. Click on "Table Editor" in the sidebar
  3. You should see a new table: n8n_chat_histories
  4. Click on the table to view entries

You'll see your conversation stored with:

  • session_id: Your unique session identifier
  • message: JSON format containing the conversation

Example stored message:

{
  "type": "human",
  "content": "Hi, I want to ask one question"
}

And the AI response:

{
  "type": "ai",
  "content": "[AI agent's response]"
}

4.3 Test Memory Persistence

Now test if the memory persists:

  1. Send another message:

    User: "I want you to remember that I love AI agents"
    
  2. Refresh the Supabase table editor

  3. You should see a new entry with this message and the AI's response

4.4 Test Memory Recall

The real test - does it remember?

  1. Restart your n8n workflow (to prove persistence works)

  2. Send a follow-up message that requires memory:

    User: "What did I just tell you to remember?"
    
  3. The AI should recall: "You mentioned that you love AI agents"

  4. Check Supabase - all messages are stored, even after restart!


Understanding the Memory Storage

Table Structure

The automatically created table n8n_chat_histories stores:

| Column | Type | Description | |--------|------|-------------| | session_id | VARCHAR | Unique identifier for each conversation | | message | JSONB | The message content in JSON format | | created_at | TIMESTAMP | When the message was stored |

Message Format

Each message is stored as JSON with:

{
  "type": "human",  // or "ai"
  "content": "The actual message text"
}

Viewing Your Conversations

In Supabase Table Editor, you can:

  • Filter by session_id to see specific conversations
  • View message history in chronological order
  • Export data for analysis or backup
  • Manually edit or delete messages if needed

Troubleshooting

Connection Failed

If you see a connection error:

  1. Check your password: Make sure you copied the correct database password
  2. Verify host: Ensure you're using the pooled connection host (not direct connection)
  3. Check port: Transaction pooler typically uses port 6543
  4. SSL settings: Supabase requires SSL - ensure it's enabled in n8n credentials

Table Not Created

If the table doesn't appear in Supabase:

  1. Make sure the workflow executed successfully
  2. Check n8n execution logs for errors
  3. Verify the Postgres credentials are saved and connected
  4. Try running the workflow again

Memory Not Persisting

If the agent doesn't remember conversations:

  1. Check that the same session_id is being used across messages
  2. Verify the context window length is set (e.g., 10)
  3. Look in Supabase Table Editor to confirm messages are being stored
  4. Restart the workflow and test again

Best Practices

1. Use Meaningful Session IDs

Create unique session IDs for each user or conversation:

// Example: User-based session ID
const sessionId = `user_${userId}_${Date.now()}`;

// Example: Channel-based session ID
const sessionId = `discord_${channelId}`;

2. Set Appropriate Context Window

Balance between context and performance:

  • Short conversations (customer support): 5-10 messages
  • Medium conversations (assistants): 10-20 messages
  • Long conversations (tutoring): 20-50 messages

3. Clean Up Old Data

Periodically remove old conversations to manage database size:

-- Delete conversations older than 30 days
DELETE FROM n8n_chat_histories 
WHERE created_at < NOW() - INTERVAL '30 days';

4. Monitor Database Usage

Check your Supabase dashboard regularly:

  • Database size: Ensure you're within your plan limits
  • Connection count: Monitor active connections
  • Query performance: Check for slow queries

Advanced Tips

Multiple Agents with Separate Memories

Use different table names for different agents:

  • Agent 1: support_agent_memory
  • Agent 2: sales_agent_memory
  • Agent 3: general_assistant_memory

Add Custom Metadata

Store additional context in the message JSON:

{
  "type": "human",
  "content": "User message",
  "metadata": {
    "channel": "discord",
    "user_id": "12345",
    "timestamp": "2024-01-01T10:00:00Z"
  }
}

Implement Memory Summarization

For very long conversations, periodically summarize earlier messages to save context window space.


Key Benefits

  • Persistent Memory: Conversations survive workflow restarts
  • Easy Setup: Simple configuration with Supabase
  • Reliable: Hosted Postgres database with automatic backups
  • Scalable: Handle thousands of conversations effortlessly
  • Flexible: Customize table structure and memory behavior
  • Cost-Effective: Supabase free tier is generous for most projects

Conclusion

You now have a fully functional persistent memory system for your AI agents! Your agents can:

✅ Remember conversations across workflow restarts
✅ Maintain context within sessions
✅ Store unlimited conversation history
✅ Scale to thousands of users

Next time you build AI agents with n8n, make sure to use Postgres memory instead of simple memory for a much better user experience!