Automation & Agents
Memory Architecture for Agents in n8n: The Window Buffer Trap vs Persistent Hybrid Memory
Why 80% of AI agents get amnesia after being deployed in Docker and how to implement decoupled memory with Postgres and SQLite WAL without blowing up the token bill.
- Date
- Oct 6, 2026
- Reading time
- 8 min
- Result
- Zero Amnesia after Restart • 68% Token Savings • Multi-Session Persistence • $0 Local Cost
Translated from the Spanish original. The code, data and READMEs on GitHub are in Spanish.
When a developer or consultant sets up their first autonomous agent in n8n, the thrill of watching the model interact through tools usually overshadows one of the most critical architectural decisions: the memory node.
By default, quick tutorials connect the Window Buffer Memory node with its default parameters (a 5-turn context). In a 5-minute local test, everything seems like magic: the agent remembers your name and the goal you gave it a couple of messages ago.
But when that workflow moves into real production in the business trenches, the house of cards collapses:
- The Docker container is restarted for a routine update and the agent suffers total amnesia, forgetting all the context of active customers.
- When you increase the buffer size to keep more history, the LLM token bill grows exponentially, paying again and again to process greetings, apologies and stale intermediate data.
- When you enable
queuemode with several n8n workers, conversations fragment because the in-memory state lives in isolated processes.
In this article from the Digital Lab (@Yeswelab_OU) we look at why this failure happens, break down the difference between durability and working memory, and show the hybrid architecture we use in production.
1. The Problem in the Trenches: Anatomy of the Window Buffer Failure
The Window Buffer Memory node stores session keys and exchanges in the RAM of the main Node.js process where n8n runs.
[ Fragile Architecture - Volatile Memory in RAM ]
┌────────────────────────────────────────────────────────┐
│ Docker container / n8n process │
│ │
│ ┌─────────────────────────┐ │
│ │ AI Agent Node │ │
│ └────────────┬────────────┘ │
│ │ (Queried every turn) │
│ ▼ │
│ ┌─────────────────────────┐ │
│ │ Window Buffer Memory │ │
│ │ (Node.js RAM) │ ◄── VOLATILE & NOT SHARED
│ │ [Turn 1, Turn 2...] │ │
│ └─────────────────────────┘ │
└────────────────────────────────────────────────────────┘
│
[Restart / Deploy / Worker 2]
▼
💥 Total amnesia / Customer state lost
The three symptoms of the collapse:
- Lifecycle Amnesia: Any server restart, image update or process crash destroys the history. If the agent was halfway through a technical support process or an onboarding setup, the customer has to start from scratch.
- Incompatibility with n8n Queue Mode: In high-load architectures where n8n distributes executions across several worker containers (
n8n worker), worker A has no access to worker B’s RAM. Each message from the same user can land on a different worker, alternating between remembering and forgetting unpredictably. - The Token Trap (Context Bloat): If you compensate for the forgetting by setting
contextWindowLength: 20, the model will reinject 20 pairs of messages on every call. For frontier models, that means spending between 15,000 and 40,000 extra input tokens per turn for a user who only asked “what was the link you sent me earlier?”.
2. The Fundamental Principle: Decouple Durability from Reasoning
To build robust systems in 2026, the engineering rule is blunt: don’t confuse the audit log with the agent’s working memory.
We need to split the system into two specialised layers:
| Layer | Responsibility | Technology | Lifecycle |
|---|---|---|---|
| Layer 1: Durable Log (Storage) | Stores the full conversation history for auditing, debugging and business continuity. | PostgreSQL / SQLite WAL | Permanent / Indexed by sessionId |
| Layer 2: Working Memory (Cognitive) | Injects into the LLM prompt only the N critical turns or a distilled summary. | Pruned buffer / Semantic window | Bounded (max. 6-8 turns or 2k tokens) |
[ Yeswelab Hybrid Architecture ]
┌──────────────────────────────────────────────────────────────────────────┐
│ n8n workflow (Webhook / Chat Trigger) │
│ │
│ 1. Extract a stable identifier: │
│ sessionId = headers['x-user-id'] || body.sender_id │
│ │
│ 2. AI Agent Node ──► Postgres Chat Memory (sub-node) │
│ ├─ contextWindowLength: 8 (Only the last 8 messages go to the LLM) │
│ └─ Table: n8n_chat_histories │
└──────────────────────────────┬───────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ External persistent database (Postgres / Supabase / SQLite WAL) │
│ │
│ id | session_id | message (JSONB) | timestamp │
│ ---+-------------------+------------------------------+-----------------│
│ 1 | usr_994821 | {"role":"human", "text":...} | 2026-10-06 09:12│
│ 2 | usr_994821 | {"role":"ai", "text":...} | 2026-10-06 09:12│
│ 3 | usr_994821 | {"role":"human", "text":...} | 2026-10-06 09:15│
└──────────────────────────────────────────────────────────────────────────┘
3. Step-by-Step Practical Implementation in n8n
Step 1: Set a Deterministic Session Key (sessionKey)
The most common mistake when configuring Postgres Chat Memory is leaving the expression empty or mapping it to volatile variables such as $execution.id. If you use the execution ID, every message will have a different sessionId and the agent won’t remember anything from the previous message.
Point the sessionKey field’s expression at the user’s unique identifier:
// If the input comes from Telegram:
={{ $('Telegram Trigger').item.json.message.chat.id }}
// If the input comes from a webhook on your API:
={{ $('Webhook').item.json.headers['x-user-id'] || $('Webhook').item.json.body.user_id }}
Step 2: Create or Validate the History Table in PostgreSQL
When you run the workflow for the first time with credentials that have CREATE permission, n8n generates the table automatically. However, on databases with restricted permissions, you need to make sure the following optimised schema exists:
CREATE TABLE IF NOT EXISTS public.n8n_chat_histories (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) NOT NULL,
message JSONB NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Essential index to avoid sequential scans in n8n:
CREATE INDEX IF NOT EXISTS idx_chat_histories_session_id
ON public.n8n_chat_histories (session_id);
Step 3: Bound the Active Window (contextWindowLength)
In the Postgres Chat Memory sub-node’s configuration:
- Context Window Length: Set it to 6 or 8. Never
0(unlimited) or values above 12. - With a value of 6, the node stores message number 50 persistently in PostgreSQL, but only injects messages 45 to 50 into the LLM prompt.
- Result: The agent keeps memory of the immediate conversation with flat, predictable token costs, while the database keeps 100% of the audit trail.
4. The Dual Track Philosophy at YesWeLab
At Yeswelab we work under the motto “Show, Don’t Sell”: we compare free, self-hosted software solutions with fast-deployment cloud alternatives.
Track A: DIY / Open Source / Self-Hosted ($0 Cost)
- Stack: n8n Community Edition on Docker Compose + PostgreSQL (or SQLite in WAL mode mounted on a persistent volume).
- Isolation: All traffic stays on the internal Docker network (
docker network create lab_internal). Zero network latency to external databases. - Maintenance: A weekly cron script to purge sessions inactive for more than 30 days:
DELETE FROM n8n_chat_histories WHERE created_at < NOW() - INTERVAL '30 days'; - Advantages: Absolute sovereignty over your users’ data, strict GDPR compliance and €0 operating cost for memory infrastructure.
Track B: Fast-Track SaaS / Cloud (Immediate Scalability)
- Stack: n8n Cloud / Enterprise + managed PostgreSQL on Supabase + Redis Chat Memory.
- Architecture: Supabase provides transactional persistence with automatic backups and RLS policies. For scenarios above 500 requests per minute, the Redis Chat Memory sub-node acts as a low-latency hot cache in front of queue-mode workers.
- Advantages: Deployment in 5 minutes without worrying about Docker volumes, automatic horizontal scaling and direct REST API access to chat histories from any web frontend.
5. A Production Checklist from the Trenches
Before launching your n8n agent with real users, go through these 5 checkpoints:
- [ ] Zero dependence on volatile memory: Remove every instance of
Window Buffer MemoryorSimple Memoryfrom production workflows. - [ ] A deterministic session key (
sessionKey): Check that the identifier is tied to the user or ticket, not to the ephemeral execution ID. - [ ] A database index: Verify that the
session_idcolumn inn8n_chat_historieshas a B-Tree index. - [ ] A strict context limit: Set
contextWindowLengthbetween 6 and 8 messages to avoid token leaks in long prompts. - [ ] Encrypted credentials: Make sure the
N8N_ENCRYPTION_KEYenvironment variable is set in your Docker so that the PostgreSQL credentials are encrypted at rest.