Cloud & Databases

TencentDB Agent Memory Storage: How Short Term and Long Term Memories Are Stored

TencentDB agent memory storage gives AI agents a persistent foundation for retaining useful facts, preferences, procedures, and experiences. Learn how to design memory schemas, manage metadata, combine relational and vector retrieval, handle…

51 min read
TencentDB Agent Memory Storage: How Short Term and Long Term Memories Are Stored
Advertisement
What You Will Learn
What Does Agent Memory Storage Actually Mean?
What Should an Agent Memory Record Contain?
Why Metadata Matters
Relational Storage Gives Memory Structure
⚡ Quick Answer
TencentDB agent memory storage converts an AI agent's temporary observations into valuable, persistent memories by intelligently identifying information with future relevance. For QA engineers and SDETs, this system ensures AI agents can recall crucial project details and debugging insights, not just chat history, to enhance testing efficiency and knowledge reuse. It prioritizes information value over mere storage capacity, building a useful knowledge base for automated quality assurance.

TencentDB Agent Memory Storage is the layer that turns an AI agent’s temporary observations into persistent information that can be reused later. If an agent needs to remember a user’s preference, a previous interaction, a project fact, or a useful experience, the system needs more than a prompt. It needs a deliberate way to represent, store, identify, update, and eventually remove that memory.

That distinction matters because storing agent memory is not the same as simply saving chat history.

Consider a QA agent working on a Playwright project. During a debugging session, it may observe hundreds of events:

User reported a checkout failure
Test started
Browser launched
Login succeeded
API request returned 200
Checkout page loaded
Payment button timed out
Authentication state was refreshed
Test passed

Should all of these become permanent memories?

Probably not.

A useful memory system should identify information that can provide future value.

For example:

The checkout tests require refreshed authentication state
before payment validation.

This is potentially reusable knowledge.

The individual browser-launch event usually is not.

That is the fundamental problem TencentDB agent memory storage needs to solve:

How do we convert useful agent experiences into structured, persistent memories without turning the database into an unlimited dump of conversations?

What Does Agent Memory Storage Actually Mean?

Agent memory storage refers to the process of persisting information that an AI agent may need beyond its immediate context.

A simplified flow looks like this:

AI Agent
   ↓
Observation
   ↓
Memory Candidate
   ↓
Classification
   ↓
Validation
   ↓
Storage
   ↓
Future Retrieval

The important word here is candidate.

Not every observation should become a memory.

For example:

InformationPermanent Memory?Reason
User said “hello”NoLow future value
Current browser is ChromiumMaybeDepends on project scope
User prefers API-based test dataYesReusable preference
Temporary network timeoutUsually noLikely transient
Project uses PlaywrightYesStable project knowledge
Previous successful debugging approachMaybePotentially reusable
Current timestampUsually noSession-specific

This is why TencentDB agent memory storage should be designed around information value rather than storage capacity.

A database can store millions of records.

That does not mean an AI agent should remember millions of irrelevant events.

What Should an Agent Memory Record Contain?

A useful memory record normally contains more than a piece of text.

At minimum, you may need:

Memory ID
Agent ID
User/Tenant ID
Memory Type
Memory Content
Created Time
Updated Time
Importance
Confidence
Expiration
Metadata
Embedding

A conceptual record could look like this:

{
  "id": "mem_001",
  "agent_id": "qa_agent",
  "tenant_id": "tenant_123",
  "memory_type": "preference",
  "content": "The team prefers API-based test data setup.",
  "importance": 0.91,
  "confidence": 0.96,
  "created_at": "2026-08-14T10:30:00Z",
  "updated_at": "2026-08-14T10:30:00Z",
  "expires_at": null
}

Now the memory is not just text.

It has identity, ownership, meaning, lifecycle, and context.

That additional information becomes extremely important when the agent has thousands or millions of memories.

Why Metadata Matters

Imagine the agent retrieves this memory:

The user prefers concise reports.

That sounds useful.

But which user?

Which project?

When was this preference recorded?

Is it still valid?

Was it explicitly stated by the user or inferred by the model?

Without metadata, the memory system cannot answer those questions reliably.

A stronger representation is:

{
  "content": "The user prefers concise reports.",
  "memory_type": "preference",
  "scope": "user",
  "confidence": 0.93,
  "source": "explicit_user_statement",
  "created_at": "2026-08-14T10:30:00Z"
}

Now retrieval can become much more intelligent.

The agent can distinguish:

User preference
vs
Project preference
vs
Temporary session information

That is one of the most important design principles behind TencentDB agent memory storage.

Image
Image

Relational Storage Gives Memory Structure

One natural foundation for agent memory is relational storage.

TencentDB for PostgreSQL provides PostgreSQL capabilities that can be used to represent structured memory records.

A simplified schema might look like:

CREATE TABLE agent_memories (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    agent_id UUID NOT NULL,
    memory_type VARCHAR(50) NOT NULL,
    content TEXT NOT NULL,
    importance NUMERIC(4,3),
    confidence NUMERIC(4,3),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    expires_at TIMESTAMPTZ
);

This is not intended as a complete production schema. It is a teaching model showing an important principle:

Memory should have structure around the content.

You can now perform deterministic queries.

For example:

SELECT id, content, importance
FROM agent_memories
WHERE agent_id = '00000000-0000-0000-0000-000000000001'
  AND memory_type = 'preference'
ORDER BY importance DESC;

This is fundamentally different from semantic retrieval.

The database is answering:

“Give me preference memories belonging to this agent.”

That kind of filtering becomes valuable before semantic search even begins.

Structured Memory vs Conversation Logs

A common beginner implementation is to store the entire conversation:

{
  "session_id": "123",
  "messages": [
    {"role": "user", "content": "Run the checkout tests"},
    {"role": "assistant", "content": "Running them now"},
    {"role": "user", "content": "The payment button failed"}
  ]
}

This can be useful for conversation history.

But conversation history and agent memory are not identical.

FeatureConversation HistoryAgent Memory
Primary purposePreserve interactionPreserve useful knowledge
ScopeUsually sessionCan span sessions
StructureMessagesMemory records
RetrievalChronological/contextualRelevance-based
LifecycleSession-orientedMemory-oriented
Example“Run the test”“Project uses Playwright”

A conversation log answers:

“What did we say?”

Agent memory answers:

“What should I remember from what we said?”

That difference is critical.

Memory Types Influence Storage Design

A memory system can store different categories of information.

A practical classification is:

Memory
├── Episodic
├── Semantic
├── Procedural
└── Preference

Each category has a different purpose.

Episodic Memory

Episodic memory represents a past event or experience.

Example:

During the previous checkout debugging session,
the payment test failed because the authentication state expired.

This is useful when the agent needs historical context.

Semantic Memory

Semantic memory represents knowledge.

Example:

The checkout service requires an authenticated session.

This is less about what happened and more about what the agent knows.

Procedural Memory

Procedural memory represents a method or process.

Example:

Create checkout test data through the API before launching the UI workflow.

It tells the agent how to perform a task.

Preference Memory

Preference memory represents how a user or team wants something done.

Example:

The team prefers concise failure summaries.

These distinctions make storage more useful because the application can retrieve memories according to their purpose.

Why One Giant Memory Table Can Become a Problem

You could technically put everything into one table:

agent_memories

and store every memory there.

That can work for an initial prototype.

But production systems need to think about:

  • Indexing
  • Filtering
  • Ownership
  • Retention
  • Memory types
  • Retrieval performance
  • Access control
  • Updates
  • Duplicate memories
  • Expired memories
  • Semantic search

A useful conceptual design might therefore separate the logical responsibilities even if they remain physically within the same PostgreSQL environment.

For example:

Memory Core
   │
   ├── Identity
   ├── Content
   ├── Type
   ├── Metadata
   ├── Lifecycle
   └── Retrieval Data

The important thing is not whether you have one table or ten tables.

The important thing is that the memory model is deliberately designed.

Where Embeddings Enter Memory Storage

Text alone cannot provide semantic similarity.

Suppose you store:

The developer prefers API-based test data generation.

Later, the user asks:

“Should we create test records through the UI or backend?”

The wording is different, but the meaning is related.

An embedding can represent the semantic meaning of the memory as a vector.

Conceptually:

memory_text = """
The developer prefers API-based test data generation.
"""

embedding = embedding_model.embed(memory_text)

memory = {
    "content": memory_text,
    "embedding": embedding
}

The embedding can then be stored alongside the memory record or in a vector-capable representation.

TencentDB for PostgreSQL supports PostgreSQL-based vector capabilities, including extensions such as pgvector, which can be used for vector search workloads.

This creates a powerful combination:

Structured Fields
       +
Memory Content
       +
Embedding
       =
Rich Memory Record

The structured fields help with filtering.

The embedding helps with semantic retrieval.

The content provides the actual information.

TencentDB vs a Dedicated Vector Database

This does not mean TencentDB should automatically replace every vector database.

Different systems optimize for different requirements.

CapabilityTencentDB for PostgreSQLDedicated Vector Database
Relational dataStrongVaries
SQLStrongVaries
TransactionsStrongDepends
Vector searchSupportedCore capability
Metadata filteringStrongUsually strong
Existing PostgreSQL integrationExcellentRequires integration
Graph-style relationshipsCan be modeledDepends
General application dataStrongUsually secondary
Specialized vector workloadsDepends on workloadOften optimized

The strategic question is not:

“Which database is better?”

It is:

“Does my agent benefit from keeping structured application data, memory metadata, and semantic memory capabilities close together?”

For applications already using PostgreSQL, that can be an important architectural advantage.

Storage Does Not Mean Permanent Storage

One of the biggest mistakes in memory design is assuming:

stored = permanent

That is not necessarily true.

A memory may have a lifecycle:

Created
   ↓
Validated
   ↓
Active
   ↓
Updated
   ↓
Decayed
   ↓
Expired / Deleted

For example, a temporary project fact might have an expiration time:

INSERT INTO agent_memories (
    id,
    tenant_id,
    agent_id,
    memory_type,
    content,
    expires_at
)
VALUES (
    gen_random_uuid(),
    '00000000-0000-0000-0000-000000000001',
    '00000000-0000-0000-0000-000000000002',
    'project',
    'The staging environment currently uses API version v2.',
    NOW() + INTERVAL '30 days'
);

After the information becomes stale, the application can remove or deprioritize it.

This is essential because stale memories can be worse than missing memories.

Imagine an agent remembering:

“The API uses version v1.”

Six months later, the application uses v3.

If the old memory remains highly ranked, the agent can confidently provide incorrect instructions.

Memory Updates Are as Important as Memory Creation

Suppose the agent initially stores:

The team uses Cypress for UI automation.

Later, the project migrates to Playwright.

The system should not blindly create:

The team uses Playwright for UI automation.

and leave the old memory untouched.

Now the database contains conflicting memories:

Cypress
Playwright

A retrieval system might return either one.

A stronger memory lifecycle supports:

Create
   ↓
Detect Related Memory
   ↓
Compare
   ↓
Update / Replace / Preserve History

A conceptual application function might look like:

def update_memory(new_memory, existing_memory):
    if new_memory["confidence"] > existing_memory["confidence"]:
        return new_memory

    return existing_memory

Again, this is only a simplified example.

Production memory reconciliation can require much richer logic.

The key lesson is:

A memory system must manage change, not just storage.

Avoid Storing Everything

Consider this agent interaction:

User: Run the tests.
Agent: Which browser?
User: Chromium.
Agent: Running now.
Agent: 17 tests passed.
User: Great.

Saving all of this permanently creates noise.

Instead, the system might extract:

No durable memory

Now consider:

User: From now on, always use Chromium for this project.

That is a strong memory candidate.

The application could produce:

{
  "memory_type": "preference",
  "content": "Use Chromium for this project's browser tests.",
  "importance": 0.92,
  "confidence": 0.99
}

The difference is not the length of the message.

It is the future value of the information.

A Useful Storage Decision Framework

Before writing a memory to TencentDB, ask:

1. Is this information reusable?
2. Is it stable?
3. Is it important?
4. Is it sufficiently trustworthy?
5. Who owns it?
6. What scope does it belong to?
7. When should it expire?
8. Could it conflict with an existing memory?
9. Does it contain sensitive information?
10. Will storing it improve future agent decisions?

If the answer to most of these questions is unclear, blindly persisting the information is usually a poor design choice.

This turns TencentDB agent memory storage into an engineering discipline rather than a simple INSERT operation.

Try This: Design One Memory Record

Imagine you are building an AI SDET assistant.

The user says:

“For our checkout tests, create test users through the API rather than the UI because it makes the suite faster.”

Design the memory.

A good starting point could be:

{
  "memory_type": "procedural",
  "scope": "project",
  "content": "Create checkout test users through the API rather than the UI.",
  "importance": 0.90,
  "confidence": 0.96,
  "source": "explicit_user_instruction"
}

Now ask yourself:

Should this memory expire?

Probably not immediately.

Should it be associated with the user?

Possibly, but project scope may be more appropriate.

Should it be embedded?

Yes, if semantic retrieval will be used.

Should it be searchable by project ID?

Absolutely.

That is the type of thinking required when designing TencentDB agent memory storage.

The Most Important Design Principle

There is a temptation to measure a memory system by how much information it can retain.

That is the wrong metric.

A better question is:

How much useful information can the agent retrieve accurately at the moment it needs it?

A memory system with 10,000 highly relevant memories can be more useful than one containing 10 million noisy records.

The storage layer should therefore optimize for:

Quality
+
Structure
+
Relevance
+
Lifecycle
+
Security
+
Retrievability

not simply record count.

When those principles are applied, TencentDB becomes more than a place to put conversation data. It can serve as a structured persistence layer for agent memories, with PostgreSQL capabilities providing the foundation for relational information and vector-enabled retrieval.

The key architectural boundary remains clear:

Agent
  ↓
Memory Decision
  ↓
Memory Representation
  ↓
TencentDB Storage
  ↓
Future Retrieval

The database stores the memory.

The agent-memory application layer decides what that memory should mean, when it should be written, how it should evolve, and when it should no longer be trusted.

That is the foundation for designing reliable persistent memory rather than simply accumulating historical data.

Designing the Memory Record for TencentDB Agent Memory Storage

TencentDB agent memory storage becomes significantly more useful when the memory record is designed as a structured data model instead of treating every memory as a plain text string. A production AI agent needs to know not only what it remembers, but also who the memory belongs to, what type of information it represents, how trustworthy it is, how important it is, and whether it is still valid.

A weak implementation might store:

"The user prefers API-based test data."

A stronger implementation stores the same knowledge with context:

{
  "content": "The user prefers API-based test data.",
  "memory_type": "preference",
  "scope": "user",
  "importance": 0.91,
  "confidence": 0.97,
  "source": "explicit_instruction"
}

The second representation gives the agent much more control.

It can retrieve preferences without retrieving project knowledge. It can prioritize high-confidence memories. It can distinguish user-level information from project-level information. It can also determine whether a memory should be updated or removed.

That is the difference between storing text and designing memory.

Start With the Memory Data Model

Before creating database tables, define what a memory means in your application.

A useful conceptual model is:

Memory
├── Identity
├── Ownership
├── Classification
├── Content
├── Retrieval Data
├── Quality Signals
└── Lifecycle

Each category answers a different engineering question.

CategoryQuestion
IdentityWhich memory is this?
OwnershipWho or what does it belong to?
ClassificationWhat kind of memory is it?
ContentWhat does the agent remember?
Retrieval DataHow can it be found semantically?
Quality SignalsHow important/trustworthy is it?
LifecycleWhen should it change or disappear?

This structure gives TencentDB agent memory storage a clear contract.

Instead of letting every part of the application write arbitrary JSON, you establish a predictable memory model.

A Practical Memory Schema

A starting PostgreSQL schema could look like this:

CREATE TABLE agent_memories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    tenant_id UUID NOT NULL,
    agent_id UUID NOT NULL,
    user_id UUID,

    memory_type VARCHAR(30) NOT NULL,
    scope VARCHAR(30) NOT NULL,

    content TEXT NOT NULL,

    importance NUMERIC(4,3) DEFAULT 0.500,
    confidence NUMERIC(4,3) DEFAULT 0.500,

    source VARCHAR(50),

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at TIMESTAMPTZ,

    metadata JSONB
);

This is a conceptual schema rather than a universal production schema.

The important lesson is the separation of responsibilities.

For example:

tenant_id

answers:

Which customer or tenant owns this information?

agent_id

answers:

Which agent is associated with this memory?

memory_type

answers:

Is this a preference, semantic fact, procedure, or experience?

scope

answers:

Is this memory specific to a user, project, agent, or another context?

importance

answers:

How valuable is this memory?

confidence

answers:

How strongly does the system believe this memory is correct?

These fields make future retrieval much more controllable.

Why memory_type Should Not Be Ignored

Imagine a database containing 50,000 memories.

Some are:

preference

Others are:

semantic

Others:

procedural

Others:

episodic

If the system stores all of them as:

type = "memory"

the retrieval layer loses valuable information.

Instead:

SELECT content
FROM agent_memories
WHERE agent_id = :agent_id
  AND memory_type = 'procedural';

Now the agent can specifically retrieve memories describing how something should be done.

For example:

Create checkout users through the API.
Initialize authentication before UI validation.
Use Chromium for checkout regression tests.

This can be much more useful when the current user request is procedural.

By contrast, an agent investigating what happened during a previous incident may want episodic memories.

Scope Is Just as Important as Type

Consider two memories:

User prefers concise reports.

and:

The checkout project uses Playwright.

The first may belong to the user.

The second belongs to the project.

A useful representation might be:

{
  "content": "User prefers concise reports.",
  "memory_type": "preference",
  "scope": "user"
}

and:

{
  "content": "Checkout project uses Playwright.",
  "memory_type": "semantic",
  "scope": "project"
}

Now retrieval can respect scope.

That prevents a common problem:

A memory that is correct in one context being incorrectly applied to another context.

Imagine the same user works on two projects:

Project A → Playwright
Project B → Cypress

If the system stores:

User uses Playwright.

as a global fact, the agent could incorrectly recommend Playwright for Project B.

A better memory might be:

Project A → uses → Playwright
Project B → uses → Cypress

This is why TencentDB agent memory storage should preserve context around the information being stored.

Image
Image

Use JSONB for Flexible Metadata

Not every memory needs exactly the same metadata.

For example, an episodic memory may have:

{
  "event_id": "checkout-incident-001",
  "duration_seconds": 184,
  "resolution": "refresh authentication state"
}

A preference memory might instead have:

{
  "preference_strength": "explicit",
  "applies_to": "test_reports"
}

This is where PostgreSQL’s JSONB type can be useful.

For example:

CREATE INDEX idx_agent_memory_metadata
ON agent_memories
USING GIN (metadata);

Now structured metadata can evolve without constantly adding new columns.

But there is an important warning.

Do not put everything inside JSONB.

If the application frequently filters on:

agent_id
memory_type
scope
created_at
expires_at

those fields generally deserve first-class columns.

A good rule is:

Frequently queried fields should be structurally visible; flexible attributes can live in metadata.

Structured Fields vs JSONB

This is a common database design decision.

ApproachAdvantageProblem
Dedicated columnsStrong structure and indexingSchema changes can be required
JSONBFlexible metadataCan become difficult to govern
Everything as JSONBVery flexible initiallyPoor long-term consistency
HybridStructure + flexibilityRequires deliberate design

For agent memory, the hybrid approach is often attractive.

For example:

Fixed:
tenant_id
agent_id
memory_type
scope
content
importance
confidence
timestamps

Flexible:
metadata
source_details
additional attributes

That gives the application predictable fields without making every future memory attribute a schema migration.

Add Vector Data Without Losing Relational Context

Semantic retrieval introduces another dimension.

Suppose the memory is:

The team prefers API-based test data because it reduces UI setup time.

The system can generate an embedding:

memory = "The team prefers API-based test data because it reduces UI setup time."

embedding = embedding_model.embed(memory)

print(len(embedding))

The resulting vector represents the semantic meaning of the memory.

A conceptual PostgreSQL definition might look like:

CREATE EXTENSION IF NOT EXISTS vector;

ALTER TABLE agent_memories
ADD COLUMN embedding vector(1536);

The exact vector dimensions must match the embedding model being used.

That detail is important.

Do not blindly copy 1536 into production.

If your embedding model produces 768 dimensions, the column needs to reflect that.

The architecture should therefore be:

Memory Text
     ↓
Embedding Model
     ↓
Vector
     ↓
Stored With Memory

rather than:

Text
 ↓
Vector
 ↓
Forget everything else

The vector is one representation of the memory.

It is not the memory’s entire identity.

Why Content and Embedding Should Stay Connected

Imagine storing:

Memory ID: 1001
Embedding: [0.02, 0.81, ...]

but losing the original content.

The vector can help identify semantic similarity, but it is not human-readable knowledge.

A complete record should maintain both:

content
embedding

along with metadata.

Conceptually:

┌─────────────────────────────┐
│ Memory                       │
├─────────────────────────────┤
│ ID                           │
│ Type                         │
│ Scope                        │
│ Content                      │
│ Embedding                    │
│ Importance                   │
│ Confidence                   │
│ Metadata                     │
│ Lifecycle                    │
└─────────────────────────────┘

This gives the retrieval system multiple signals.

Importance and Confidence Are Different

These two fields are easy to confuse.

Consider:

The user explicitly prefers API-based test data.

You might assign:

confidence = 0.99
importance = 0.85

Why?

Because the system is highly confident the statement is correct, but its importance may not be absolute.

Now consider:

The user might prefer dark mode.

Perhaps:

confidence = 0.55
importance = 0.40

The agent should not treat speculation as fact.

This distinction can influence retrieval.

A conceptual scoring function could be:

def memory_score(similarity, importance, confidence):
    return (
        similarity * 0.60
        + importance * 0.20
        + confidence * 0.20
    )

Again, this is a teaching example, not a universal formula.

The important concept is:

Semantic relevance
       +
Memory importance
       +
Memory confidence
       =
Better retrieval ranking

Store the Source of a Memory

Where did the memory come from?

That question becomes extremely important when memories conflict.

Consider:

source = "explicit_user_instruction"

versus:

source = "llm_inference"

These should not necessarily have the same trust level.

A memory record could contain:

{
  "content": "Use Playwright for browser automation.",
  "source": "explicit_user_instruction",
  "confidence": 0.99
}

while an inferred memory could be:

{
  "content": "The user probably prefers Playwright.",
  "source": "llm_inference",
  "confidence": 0.62
}

This gives your memory system an additional quality signal.

It also makes debugging easier.

When the agent produces an incorrect answer, you can inspect:

Where did this memory originate?
When was it created?
What confidence did it have?
What source produced it?

That is much harder to determine if your database contains nothing but anonymous text blobs.

Memory IDs Enable Lifecycle Management

Every persistent memory should have a stable identifier.

For example:

mem_7c4e9a...

Why?

Because eventually the system will need to perform operations such as:

Create
Read
Update
Merge
Expire
Delete
Audit

For example:

UPDATE agent_memories
SET
    content = :new_content,
    confidence = :confidence,
    updated_at = NOW()
WHERE id = :memory_id;

Without stable identifiers, updating a specific memory becomes much more difficult.

This becomes particularly important when two memories express related but slightly different information.

Duplicate Memories Are a Real Problem

Suppose the agent stores this:

The team prefers API-based test data.

Then later stores:

The team prefers creating test data through APIs.

Semantically, these may represent the same memory.

A naive system creates two records.

After months of operation, you could have:

10,000 memories
↓
3,000 are duplicates or near-duplicates

This increases retrieval noise.

A smarter workflow is:

New Memory
    ↓
Semantic Similarity Check
    ↓
Existing Related Memory?
    ├── No → Create
    └── Yes
          ↓
     Compare Facts
          ↓
     Update / Merge / Preserve

A conceptual implementation might look like:

similar = find_similar_memories(
    embedding=new_embedding,
    threshold=0.90
)

if not similar:
    create_memory(new_memory)
else:
    reconcile_memory(new_memory, similar)

This is one of the places where semantic retrieval becomes useful during storage, not just during retrieval.

TencentDB Agent Memory Storage vs Redis

Redis can be excellent for fast temporary state.

For example:

Agent Session
      ↓
Redis
      ↓
Short-lived Context

That makes sense when you need:

  • Fast reads
  • Session state
  • Temporary context
  • Caching
  • Short-lived data

But persistent agent memory may require:

  • Relational structure
  • Durable records
  • Complex filtering
  • Metadata
  • Transactions
  • Vector retrieval
  • Lifecycle management

A simplified comparison:

RequirementRedisTencentDB for PostgreSQL
Temporary stateExcellentGood
Relational dataLimitedExcellent
SQL queryingNoYes
Durable structured memoryPossibleStrong fit
Vector capabilityAvailable through ecosystemPostgreSQL vector capabilities
Complex relationshipsApplication-dependentRelational model
Session cachingExcellentNot primary purpose

This does not make Redis inferior.

It means the two systems solve different problems.

A mature agent may even use both:

                 AI Agent
                    │
          ┌─────────┴─────────┐
          ↓                   ↓
       Redis             TencentDB
   Working State       Persistent Memory

The strategic decision is based on memory lifetime and access pattern, not popularity.

Memory Storage Should Support Expiration

Not every memory should live forever.

Consider:

The staging API currently uses version 2.

That information may become obsolete.

Your record can include:

expires_at TIMESTAMPTZ

Then a cleanup operation might look like:

DELETE FROM agent_memories
WHERE expires_at IS NOT NULL
  AND expires_at < NOW();

In production, you may choose a softer approach:

Active
 ↓
Stale
 ↓
Low priority
 ↓
Archived
 ↓
Deleted

This can be better than immediately deleting everything.

The right strategy depends on the application’s requirements.

Design Memory Ownership Before Production

A multi-tenant AI system may look like:

Tenant A
 ├── Agent 1
 └── Agent 2

Tenant B
 ├── Agent 3
 └── Agent 4

Memory must respect those boundaries.

A memory belonging to Tenant A must never become retrievable by Tenant B.

That makes:

tenant_id

more than a convenience field.

It becomes a security boundary.

A query should therefore be scoped appropriately:

SELECT *
FROM agent_memories
WHERE tenant_id = :tenant_id
  AND agent_id = :agent_id
ORDER BY created_at DESC;

For stronger protection, PostgreSQL Row-Level Security can also be incorporated into the design.

The exact security model should follow your tenancy architecture, but the principle is straightforward:

Never rely only on the AI model to enforce memory isolation.

Database-level controls should participate in the security design.

Try an Engineering Challenge

Imagine these memories exist:

M1:
Project A uses Playwright.

M2:
Project B uses Cypress.

M3:
The user prefers concise reports.

M4:
Project A test data should be created through APIs.

M5:
The staging API currently uses v2.

Now the user asks:

“How should I prepare test data for Project A?”

Which memories should be retrieved?

A strong candidate set is:

M4 → Highly relevant
M1 → Potentially relevant
M3 → Not relevant
M2 → Irrelevant
M5 → Possibly relevant depending on the task

Notice what happened.

The database did not simply retrieve “all memories for the user.”

The system needs to combine:

Scope
+
Memory Type
+
Semantic Similarity
+
Importance
+
Freshness

That is where well-designed TencentDB agent memory storage becomes valuable.

A Better Mental Model for Memory Records

Do not think of a memory as:

TEXT

Think of it as:

┌──────────────────────────────────────┐
│             MEMORY                   │
├──────────────────────────────────────┤
│ Identity                             │
│ Ownership                            │
│ Scope                                │
│ Type                                 │
│ Content                              │
│ Embedding                            │
│ Importance                           │
│ Confidence                           │
│ Source                               │
│ Metadata                             │
│ Created / Updated                    │
│ Expiration                           │
└──────────────────────────────────────┘

That model changes how you design the database.

You stop asking:

“Where do I save this sentence?”

and start asking:

“What does this information represent, who owns it, how trustworthy is it, how should it be retrieved, and how long should it remain valid?”

That is the mindset required for production agent memory.

Storage Quality Determines Retrieval Quality

One final principle is worth remembering.

A poor storage model creates problems later.

If you store:

unstructured content
+
no scope
+
no type
+
no ownership
+
no confidence
+
no lifecycle

then retrieval has very little information with which to make good decisions.

But if every memory has meaningful structure:

Content
+
Type
+
Scope
+
Ownership
+
Confidence
+
Importance
+
Embedding
+
Lifecycle

the retrieval layer has significantly more signals to work with.

That means TencentDB agent memory storage should be designed backward from the questions your agent will eventually need to answer.

Ask:

What will the agent need to retrieve?

Then determine:

What information must be stored to make that retrieval accurate?

Then design:

What schema, indexes, metadata, vectors, and lifecycle rules support that requirement?

That approach is far more effective than starting with a database table and deciding what to put inside it afterward.

Retrieving the Right Memories From TencentDB

TencentDB agent memory storage becomes truly useful when the stored information can be found accurately at the moment an AI agent needs it. Writing memories into a database is only half of the problem. The other half is deciding which memories deserve to be retrieved for a particular request.

Imagine an AI testing assistant has accumulated these memories:

Project A uses Playwright.
Project B uses Cypress.
The user prefers concise reports.
Checkout test data should be created through APIs.
The staging API currently uses version 2.
A previous checkout failure was caused by expired authentication.

Now the user asks:

“How should I prepare checkout data for Project A?”

A naive implementation might retrieve every memory associated with that user.

That would be a mistake.

The useful memories are likely:

Project A uses Playwright.
Checkout test data should be created through APIs.

The staging API version might become relevant later.

The reporting preference is irrelevant.

Project B’s Cypress configuration is unrelated.

This gives us an important principle:

Good memory storage is not measured by how much information is retained. It is measured by how accurately relevant information can be found.

Storage and Retrieval Are Two Different Problems

It helps to separate the lifecycle into two independent operations:

             MEMORY LIFECYCLE

       WRITE                    READ
         │                       │
         ↓                       ↓
   Extract Memory          User Request
         │                       │
         ↓                       ↓
    Classify                  Query
         │                       │
         ↓                       ↓
     Validate              Find Candidates
         │                       │
         ↓                       ↓
 TencentDB Storage          Rank Results
                                 │
                                 ↓
                         Agent Context

The write side answers:

What should we remember?

The read side answers:

What should we remember right now?

Those are not the same question.

A memory can be extremely valuable in general but irrelevant to the current task.

That is why TencentDB agent memory storage needs to be designed together with retrieval logic.

Exact Matching Is Not Enough

Suppose the database contains:

The developer prefers API-based test data creation.

The user later asks:

“Should I create checkout users through the backend before starting the browser test?”

There may be no exact keyword match.

The stored memory says:

API-based test data

while the query says:

backend
browser test
create checkout users

A traditional SQL query such as:

SELECT content
FROM agent_memories
WHERE content ILIKE '%backend%';

could fail to find the memory.

This is where semantic retrieval becomes valuable.

Instead of comparing only words, the system can compare the semantic representation of the query with the semantic representation of stored memories.

Semantic Search Changes the Retrieval Model

Conceptually:

User Question
     ↓
Embedding Model
     ↓
Query Vector
     ↓
Vector Search
     ↓
Similar Memory Vectors
     ↓
Relevant Memories

A simplified Python example:

query = "Should checkout users be created through the backend?"

query_embedding = embedding_model.embed(query)

results = search_memory_vectors(
    vector=query_embedding,
    top_k=5
)

for result in results:
    print(result["content"])

The result could include:

The team prefers API-based test data creation.

even though the words are not identical.

This is one reason PostgreSQL-based vector capabilities can be useful in TencentDB agent memory storage. Tencent Cloud documents vector search capabilities for TencentDB for PostgreSQL, including pgvector-based approaches for AI workloads.

But Vector Similarity Alone Is Not Enough

Here is a subtle but important problem.

Suppose your database contains:

Memory A:
Project A uses Playwright.

Memory B:
Project B uses Playwright.

Memory C:
The user prefers Playwright.

Memory D:
The company previously used Playwright.

The user asks:

“How should I configure tests for Project A?”

All four memories may be semantically similar.

But only one is directly associated with Project A.

A pure vector search might return all four.

That is why strong retrieval combines:

Semantic similarity
+
Metadata filtering
+
Scope
+
Freshness
+
Importance
+
Confidence

The retrieval problem is therefore not:

Find similar text.

It is:

Find useful memories for this specific task.

Filter Before You Rank

One useful strategy is to narrow the candidate set before performing expensive ranking.

For example:

SELECT id, content, memory_type, importance, confidence
FROM agent_memories
WHERE tenant_id = :tenant_id
  AND project_id = :project_id
  AND expires_at IS NULL
     OR expires_at > NOW();

The exact SQL should include proper parentheses in production to ensure the intended boolean precedence.

A clearer version is:

SELECT id, content, memory_type, importance, confidence
FROM agent_memories
WHERE tenant_id = :tenant_id
  AND project_id = :project_id
  AND (
      expires_at IS NULL
      OR expires_at > NOW()
  );

Now the retrieval system is not searching the entire memory universe.

It is searching memories that already satisfy basic constraints.

Then semantic ranking can operate on that smaller candidate set.

The conceptual flow becomes:

All Memories
     ↓
Tenant Filter
     ↓
Agent / Project Filter
     ↓
Memory Type Filter
     ↓
Expiration Filter
     ↓
Semantic Search
     ↓
Ranking
     ↓
Top Memories

This can improve both relevance and efficiency.

Image

Top-K Retrieval is a Starting Point, Not a Complete Strategy

Vector systems commonly use a top_k value.

For example:

results = vector_search(
    query_embedding,
    top_k=5
)

This means:

Return the five closest memories.

But the five closest memories are not automatically the five most useful memories.

Imagine the results:

1. Similarity = 0.94 → Project B uses Playwright
2. Similarity = 0.93 → User prefers Playwright
3. Similarity = 0.92 → Project A uses Playwright
4. Similarity = 0.91 → Company previously used Playwright
5. Similarity = 0.90 → Playwright was used in an old project

For a Project A request, memory #3 may be much more useful than #1.

This is why a second ranking stage can help.

Add a Relevance Score

A conceptual ranking formula might be:

def score_memory(similarity, importance, confidence, freshness):
    return (
        similarity * 0.55
        + importance * 0.20
        + confidence * 0.15
        + freshness * 0.10
    )

This is not a universal formula.

The weights depend on your application.

For a compliance agent, confidence may deserve more weight.

For a rapidly changing operations agent, freshness may be more important.

For a personal assistant, user-specific relevance could become a major factor.

The important lesson is:

Semantic similarity should be a signal, not the entire decision.

Freshness Prevents Stale Memory From Winning

Consider this memory:

The staging API uses version 1.

It was stored two years ago.

Now the current memory says:

The staging API uses version 3.

A semantic search may find both.

If the old memory has a very similar embedding, it could still appear among the top results.

This creates a dangerous situation.

The agent could receive:

v1
v3

and choose incorrectly.

One approach is to introduce freshness.

A simple conceptual function could be:

from datetime import datetime

def freshness(memory_age_days):
    return 1 / (1 + memory_age_days / 30)

This gives newer memories more weight.

But freshness should not automatically override everything.

Some memories are intentionally permanent.

For example:

The project uses Page Object Model.

might remain valid for years.

Others may become obsolete quickly:

The staging API uses version 2.

This is why freshness should work together with memory type and expiration policy.

Expiration Is Different From Freshness

These concepts are related but not identical.

Freshness asks:

How recently was this memory updated?

Expiration asks:

Is this memory still allowed to be used?

For example:

Created:
August 1

Expires:
September 1

On August 20:

Fresh enough → Yes
Expired → No

On September 10:

Fresh enough → Maybe
Expired → Yes

An expired memory should generally not be returned as an active memory.

That makes lifecycle metadata an important part of TencentDB agent memory storage.

Retrieval by Memory Type

The user request itself can suggest which memory categories are useful.

Suppose the user asks:

“What happened when we debugged checkout last time?”

The retrieval layer should prioritize:

episodic

Suppose they ask:

“How should we prepare checkout data?”

Prioritize:

procedural

Suppose they ask:

“What does this project use for browser automation?”

Prioritize:

semantic

Suppose they ask:

“How do I want the test report formatted?”

Prioritize:

preference

This can be represented in application logic:

MEMORY_PRIORITY = {
    "debugging_history": ["episodic", "semantic"],
    "how_to": ["procedural", "semantic"],
    "project_facts": ["semantic", "procedural"],
    "user_preferences": ["preference"]
}

This makes retrieval more intentional.

Metadata Filtering vs Vector Search

These approaches are complementary.

TechniqueAnswersStrength
Metadata filter“Which memories are allowed?”Precision
Keyword search“Which memories contain these words?”Exact matching
Vector search“Which memories mean something similar?”Semantic relevance
Reranking“Which candidates are most useful?”Contextual relevance

A robust system can combine all four.

For example:

User Query
    ↓
Metadata Filter
    ↓
Keyword / Vector Candidate Search
    ↓
Relevance Reranking
    ↓
Deduplication
    ↓
Context Selection

That is much more powerful than simply running one similarity query.

Avoid Context Flooding

Imagine retrieval returns 100 memories.

You could technically put all 100 into the LLM prompt.

But should you?

Probably not.

The model’s context is a resource.

Too much irrelevant memory can cause:

  • Higher token usage
  • Increased latency
  • More expensive inference
  • Conflicting information
  • Reduced attention to important facts
  • Poorer responses

Instead, retrieval should aim for a small, useful context.

For example:

MAX_MEMORIES = 5

memories = retrieve_memories(
    query=query,
    top_k=MAX_MEMORIES
)

But even five may be too many depending on memory length.

A better production strategy can impose both:

Maximum memory count
+
Maximum memory token budget

For example:

MAX_MEMORY_TOKENS = 1200

Then the system selects memories until the budget is reached.

This makes memory retrieval part of context engineering, not simply database querying.

Memory Compression Can Reduce Noise

Suppose the agent has stored:

The user asked for Playwright examples.
The user prefers Playwright.
The user selected Playwright for the project.
The project uses Playwright.
The developer chose Playwright.

Five memories may actually represent one broader fact.

A memory consolidation process could produce:

The project uses Playwright as its primary browser automation framework.

The system can then retain the consolidated memory while reducing duplicates.

Conceptually:

Memory A ─┐
Memory B ─┤
Memory C ─┼──→ Consolidation → Canonical Memory
Memory D ─┤
Memory E ─┘

This is especially valuable as memory volume increases.

Deduplication Should Happen Before Context Injection

Suppose retrieval returns:

1. Team prefers API test data.
2. API-based test data is preferred by the team.
3. Test data should be created using APIs.

Giving all three to the LLM wastes context.

A simple application-level deduplication strategy could be:

unique = []

for memory in memories:
    if not is_semantically_duplicate(memory, unique):
        unique.append(memory)

The final context could contain:

The team prefers API-based test data creation.

One strong memory is better than three repetitive memories.

A More Complete Retrieval Function

Putting these ideas together:

def retrieve_agent_memory(
    query,
    tenant_id,
    agent_id,
    project_id=None
):
    candidates = search_database(
        tenant_id=tenant_id,
        agent_id=agent_id,
        project_id=project_id
    )

    query_embedding = embed(query)

    candidates = semantic_rank(
        candidates,
        query_embedding
    )

    candidates = rerank(
        candidates,
        importance=True,
        confidence=True,
        freshness=True
    )

    candidates = deduplicate(candidates)

    return fit_context_budget(
        candidates,
        max_tokens=1200
    )

This example demonstrates an important architectural progression:

Database
     ↓
Filtering
     ↓
Semantic Search
     ↓
Reranking
     ↓
Deduplication
     ↓
Context Budget
     ↓
LLM

The database provides the persistence layer.

The application provides the intelligence around retrieval.

TencentDB Agent Memory Storage vs Traditional RAG

There is another important comparison.

Traditional RAG usually starts with:

Documents
   ↓
Chunking
   ↓
Embeddings
   ↓
Vector Database
   ↓
Search
   ↓
LLM

Agent memory can look similar, but the information lifecycle is different.

Traditional RAGAgent Memory
Usually retrieves external knowledgeRetrieves learned/persistent agent context
Documents are primary sourceExperiences, facts, preferences, procedures
Chunking is commonMemory extraction is common
Retrieval is often query-drivenRetrieval can be task + identity + scope driven
Source documents are relatively stableMemories can change
Memory ownership is less centralUser/agent/tenant ownership is critical
Expiration may be uncommonMemory lifecycle can be essential

This distinction prevents another common design mistake:

Agent memory is not simply RAG with a different name.

RAG retrieves knowledge from a corpus.

Agent memory manages information that the agent is expected to retain and reuse across interactions.

There can be overlap, but the lifecycle is different.

Build Retrieval Around the User’s Actual Question

Consider three requests.

Request 1

“What framework does Project A use?”

Retrieve:

semantic
project-scoped
high-confidence
current

Request 2

“What happened during yesterday’s checkout incident?”

Retrieve:

episodic
project-scoped
recent

Request 3

“How do I want the final report?”

Retrieve:

preference
user-scoped
high-confidence

The same database can support all three.

The retrieval strategy changes according to the question.

That is the key.

Interactive Challenge: Choose the Correct Memories

Assume these memories exist:

M1:
Project Alpha uses Playwright.

M2:
Project Beta uses Cypress.

M3:
The user prefers concise reports.

M4:
Project Alpha creates test users through APIs.

M5:
The user previously debugged a checkout timeout.

M6:
Project Alpha staging currently uses API v3.

Question:

“Generate a strategy for preparing checkout tests in Project Alpha.”

Which memories should the agent prioritize?

Think before reading the answer.

The strongest candidates are likely:

M1 → Project technology
M4 → Test-data procedure
M6 → Current project environment

Potentially useful:

M5 → Historical debugging context

Probably irrelevant:

M2 → Different project
M3 → Report formatting preference

This demonstrates why retrieval must understand scope and task relevance, not simply similarity.

The Retrieval Pipeline You Should Remember

A practical mental model is:

                  USER REQUEST
                       │
                       ↓
                Query Understanding
                       │
                       ↓
               ┌───────────────┐
               │ Query Vector  │
               └───────┬───────┘
                       ↓
               TencentDB Memory
                       │
            ┌──────────┴──────────┐
            ↓                     ↓
      Metadata Filter        Vector Search
            │                     │
            └──────────┬──────────┘
                       ↓
                  Candidate Set
                       ↓
                    Rerank
                       ↓
                  Deduplicate
                       ↓
                Context Budget
                       ↓
                  AI Agent

The crucial point is that TencentDB agent memory storage should not end at the SELECT or vector-search operation.

The retrieval pipeline determines whether stored information becomes useful knowledge or simply becomes database noise.

A Production-Oriented Retrieval Checklist

Before calling your memory retrieval system production-ready, ask:

□ Can memories be filtered by tenant?
□ Can memories be filtered by agent?
□ Can memories be filtered by project?
□ Can memories be filtered by type?
□ Are expired memories excluded?
□ Can semantic similarity be used?
□ Are importance and confidence considered?
□ Are stale memories penalized?
□ Are duplicates removed?
□ Is there a context/token budget?
□ Can conflicting memories be detected?
□ Can memory sources be inspected?
□ Can retrieval decisions be logged?

If several answers are “no,” the storage layer may work technically while the overall agent memory experience remains unreliable.

The recommended H1 for the article remains “TencentDB Agent Memory Storage: How Memories Are Stored”. This section deliberately continues that exact storage-focused search topic rather than turning the article into a generic architecture or RAG tutorial.

The most important idea is simple:

Store memories with enough structure that the retrieval layer can distinguish what is relevant, current, trustworthy, and allowed to reach the agent’s context.

A well-designed memory database does not merely answer “What have we stored?”

It enables the much more valuable question:

“Which stored memory should this agent use for this request, right now?”

Building a Production-Ready TencentDB Agent Memory Storage Workflow

TencentDB agent memory storage becomes valuable in a real AI application only when the complete lifecycle works reliably: a memory must be identified, validated, stored, retrieved, updated, and eventually removed when it is no longer useful.

A simple prototype might do this:

memory_db.insert("The project uses Playwright.")

That is enough to demonstrate persistence.

It is not enough to build dependable agent memory.

A production-oriented implementation needs to answer questions such as:

Who owns this memory?
What project does it belong to?
How confident are we?
How important is it?
Is it still valid?
Could another memory contradict it?
How will we retrieve it?
Should it be included in the agent context?
When should it disappear?

This changes the design from:

LLM → Database

to:

LLM
 ↓
Memory Decision
 ↓
Memory Validation
 ↓
Memory Representation
 ↓
TencentDB
 ↓
Retrieval
 ↓
Ranking
 ↓
Context Selection
 ↓
LLM

That complete loop is what makes persistent agent memory practical.

Start With a Clear Memory Lifecycle

A useful lifecycle is:

Candidate
   ↓
Validate
   ↓
Normalize
   ↓
Deduplicate
   ↓
Store
   ↓
Retrieve
   ↓
Rank
   ↓
Use
   ↓
Update / Expire / Delete

Each stage solves a different problem.

For example, the agent might observe:

The user says:
"Please always create test data through the API."

The application should not immediately write the raw sentence into the database.

Instead, it can transform it into:

{
  "memory_type": "preference",
  "scope": "project",
  "content": "Create test data through the API.",
  "importance": 0.91,
  "confidence": 0.99,
  "source": "explicit_user_instruction"
}

Now the memory has meaning beyond its original wording.

That normalization step is particularly important when building TencentDB agent memory storage because consistent records make later retrieval and maintenance much easier.

Separate Memory Extraction From Database Writes

One of the strongest architectural decisions is to avoid allowing the LLM to directly control database writes without validation.

A safer design looks like:

Conversation
     ↓
Memory Extraction
     ↓
Structured Memory Candidate
     ↓
Validation Layer
     ↓
Policy Checks
     ↓
Deduplication
     ↓
TencentDB

For example:

candidate = extract_memory(conversation)

if not candidate:
    return

if not validate_memory(candidate):
    return

if is_duplicate(candidate):
    reconcile_memory(candidate)
else:
    save_memory(candidate)

This creates a boundary between AI-generated decisions and database persistence.

That boundary matters because an LLM can misunderstand a statement.

Suppose a user says:

“We are testing whether Cypress could replace Playwright.”

The agent should not automatically create:

The project uses Cypress.

The conversation describes an experiment, not a confirmed project fact.

A validation layer can prevent this kind of incorrect persistence.

Use Memory Policies

A practical memory system should define rules for what can be stored.

For example:

MEMORY_POLICY = {
    "preference": {
        "requires_confirmation": False,
        "default_importance": 0.80
    },
    "project_fact": {
        "requires_confirmation": False,
        "default_importance": 0.75
    },
    "inference": {
        "requires_confirmation": True,
        "default_importance": 0.40
    }
}

These values are examples, not universal standards.

The important idea is that not all memory candidates should receive equal treatment.

You could classify information as:

Memory CandidateStorage Policy
Explicit user preferenceUsually store
Confirmed project factStore
Temporary observationUsually avoid
Model speculationValidate carefully
Sensitive informationApply stricter controls
Contradictory factReconcile before storing
Expired informationRemove or archive

This makes the memory system predictable.

Memory Validation Should Happen Before Persistence

Consider:

User:
"We might migrate to Playwright next quarter."

A naive extraction model might produce:

{
  "content": "The team uses Playwright."
}

That is incorrect.

A better extraction result is:

{
  "content": "The team may migrate to Playwright next quarter.",
  "memory_type": "planned_change",
  "confidence": 0.70,
  "expires_at": "2026-12-01T00:00:00Z"
}

The wording preserves uncertainty.

This is an important principle:

Memory should preserve the certainty of the information it represents.

Do not convert:

might
probably
considering
possibly

into:

is
uses
always
requires

just because the database needs a clean sentence.

Design Idempotent Memory Writes

A production system may process the same conversation multiple times.

For example:

Retry
Webhook replay
Worker restart
Network timeout
Duplicate event

If every retry creates another memory, the database quickly accumulates duplicates.

A better strategy uses an idempotency key.

For example:

CREATE TABLE agent_memories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    source_event_id UUID,
    content TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

Then:

CREATE UNIQUE INDEX uq_memory_source_event
ON agent_memories (tenant_id, source_event_id);

Now the same event can be processed safely without producing unlimited duplicate records.

This is an often-overlooked aspect of TencentDB agent memory storage.

Memory reliability depends not only on AI quality but also on ordinary distributed-system engineering.

Index for the Queries You Actually Run

A memory database can become slow if indexes are added randomly.

Start by understanding retrieval patterns.

Suppose most requests look like:

tenant_id
+
agent_id
+
memory_type

Then an index might be:

CREATE INDEX idx_memory_agent_type
ON agent_memories (
    tenant_id,
    agent_id,
    memory_type
);

If project-scoped retrieval is common:

CREATE INDEX idx_memory_project
ON agent_memories (
    tenant_id,
    project_id,
    memory_type
);

For expiration cleanup:

CREATE INDEX idx_memory_expiration
ON agent_memories (expires_at);

The principle is simple:

Indexes should follow access patterns, not assumptions.

Do not create ten indexes because the table contains ten fields.

Every index has maintenance cost.

Image
Image

Relational Indexes and Vector Indexes Solve Different Problems

This distinction is important.

A relational index can efficiently answer:

Find memories belonging to Project A.

A vector index can efficiently answer:

Find memories semantically similar to this question.

They complement each other.

Retrieval NeedBest Mechanism
Tenant filteringRelational index
Agent filteringRelational index
Memory type filteringRelational index
Date/expiration filteringRelational index
Exact identifiersB-tree-style indexes
Semantic similarityVector index
Similar conceptsVector search
Combined retrievalBoth

A strong system can therefore perform:

Tenant Filter
      ↓
Project Filter
      ↓
Vector Search
      ↓
Reranking

rather than forcing vector similarity to solve every retrieval problem.

Do Not Treat Vector Similarity as Truth

Suppose the vector search returns:

Memory A:
Project Alpha uses Playwright.

Memory B:
Project Beta uses Playwright.

Memory C:
The user previously used Playwright.

Memory D:
The company migrated away from Playwright last year.

All four could be semantically similar to:

“What browser automation framework does Alpha use?”

Similarity tells you:

“These memories are related.”

It does not necessarily tell you:

“This is the correct answer.”

That is why metadata, scope, freshness, confidence, and conflict resolution remain important.

The database provides retrieval capabilities.

Your application must define the meaning of the retrieved results.

Build Conflict Detection Into the Workflow

Memory conflicts are inevitable.

Suppose the database contains:

Memory 1:
Project Alpha uses Cypress.

Memory 2:
Project Alpha uses Playwright.

The system should not blindly send both to the model.

A conflict detection layer could flag:

def detect_conflict(existing, new):
    return (
        existing["scope"] == new["scope"]
        and existing["memory_type"] == new["memory_type"]
        and contradicts(existing["content"], new["content"])
    )

Then the application can decide:

Conflict detected
      ↓
Compare confidence
      ↓
Compare timestamps
      ↓
Check source
      ↓
Update / merge / archive

For example:

Older:
"The project uses Cypress."

Newer explicit instruction:
"The project migrated to Playwright."

The system might mark the first memory as superseded.

Use Memory Status Instead of Immediate Deletion

Rather than immediately deleting an old memory, you can maintain status:

active
superseded
expired
archived
deleted

A schema might contain:

ALTER TABLE agent_memories
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';

Then retrieval can use:

SELECT content
FROM agent_memories
WHERE tenant_id = :tenant_id
  AND agent_id = :agent_id
  AND status = 'active';

This gives you historical traceability without allowing stale information into normal retrieval.

For debugging an AI agent, that history can be extremely useful.

Memory Reconciliation Is More Important Than Memory Creation

A common beginner workflow is:

New information
      ↓
INSERT

A mature workflow is:

New information
      ↓
Find related memories
      ↓
Determine relationship
      ↓
Create / update / merge / supersede

The relationship might be:

NEW
DUPLICATE
UPDATE
CONTRADICTION
ADDITION
TEMPORARY

For example:

Existing:
"Project uses Playwright."

New:
"Project uses Playwright with TypeScript."

This may be an addition rather than a contradiction.

Another example:

Existing:
"Project uses Cypress."

New:
"Project migrated to Playwright."

This is probably a superseding update.

The ability to distinguish these cases determines whether the memory store becomes increasingly intelligent or increasingly noisy.

Use Transactions for Related Updates

Suppose one memory is being replaced by another.

You may need to:

1. Insert new memory
2. Mark old memory as superseded
3. Record relationship

These operations should ideally be atomic.

A conceptual transaction:

BEGIN;

INSERT INTO agent_memories (
    tenant_id,
    agent_id,
    memory_type,
    content,
    status
)
VALUES (
    :tenant_id,
    :agent_id,
    'semantic',
    'Project migrated to Playwright.',
    'active'
);

UPDATE agent_memories
SET status = 'superseded',
    updated_at = NOW()
WHERE id = :old_memory_id;

COMMIT;

If something fails, the transaction can roll back.

This is one area where a relational database foundation can be particularly useful.

Keep Memory Relationships

Sometimes the new memory does not simply replace the old one.

You may want to know:

Memory B supersedes Memory A
Memory C supports Memory B
Memory D contradicts Memory B

A relationship table can model this:

CREATE TABLE memory_relationships (
    source_memory_id UUID NOT NULL,
    target_memory_id UUID NOT NULL,
    relationship_type VARCHAR(30) NOT NULL,

    PRIMARY KEY (
        source_memory_id,
        target_memory_id,
        relationship_type
    )
);

Then:

Memory A
   │
   └── superseded_by → Memory B

This turns the memory system into more than a collection of independent records.

It becomes a connected knowledge structure.

TencentDB Agent Memory Storage vs Redis for Production Memory

A useful production architecture may use both TencentDB and Redis rather than choosing one universally.

For example:

                    AI Agent
                       │
          ┌────────────┴────────────┐
          ↓                         ↓
       Redis                    TencentDB
   Working Context          Persistent Memory
          │                         │
   Fast / Temporary          Durable / Structured

Redis can hold:

Current conversation state
Temporary tool results
Short-lived agent state
Caching

TencentDB can hold:

Persistent preferences
Project knowledge
Long-term procedural memories
Memory metadata
Historical records
Relational application data

The comparison is therefore architectural:

RequirementRedisTencentDB
Temporary stateExcellentGood
Persistent relational memoryLimited fitStrong fit
SQLNoYes
Complex metadataPossibleStrong
Transactional updatesAvailableStrong relational support
Vector-enabled PostgreSQL workflowNot its primary modelStrong fit for PostgreSQL-based designs
CacheExcellentNot primary purpose

A hybrid architecture is often more realistic than forcing one system to handle every type of state.

Add Observability to Memory Operations

If your AI agent gives a wrong answer, you need to know why.

A memory retrieval log could capture:

{
  "request_id": "req_123",
  "agent_id": "agent_001",
  "query": "How should checkout data be created?",
  "candidate_count": 18,
  "retrieved_count": 5,
  "top_similarity": 0.93,
  "filtered_expired": 2,
  "filtered_wrong_scope": 7,
  "deduplicated": 1
}

Now debugging becomes possible.

You can ask:

Did retrieval fail?
Did filtering remove the correct memory?
Was the memory stale?
Was the wrong memory ranked higher?
Did the LLM ignore correct context?

Without observability, AI memory failures can become extremely difficult to diagnose.

Measure Memory Retrieval Quality

Do not only measure database performance.

Measure whether the right memory was retrieved.

Useful metrics can include:

Memory retrieval precision
Memory retrieval recall
Top-K relevance
Duplicate rate
Conflict rate
Stale-memory rate
Average retrieval latency
Memory write rejection rate
Context token usage

For example:

Query:
"How do we create checkout test users?"

Expected memory:
"Create checkout users through the API."

Retrieved:
"Project uses Playwright."

The query technically returned a related memory.

But retrieval quality is still poor.

This is why AI memory systems need evaluation datasets.

Create a Small Memory Evaluation Set

You can start with a simple JSON file:

[
  {
    "query": "How should checkout users be created?",
    "expected_memory": "Create checkout users through the API."
  },
  {
    "query": "Which browser framework does Project Alpha use?",
    "expected_memory": "Project Alpha uses Playwright."
  }
]

Then evaluate retrieval automatically:

for test in evaluation_cases:
    results = retrieve_memory(test["query"])

    assert contains_expected_memory(
        results,
        test["expected_memory"]
    )

This turns memory retrieval into something measurable.

That is a major step toward production quality.

Security Must Be Part of Memory Design

Persistent memory can contain information that should not be globally accessible.

Potential examples include:

User preferences
Project information
Internal workflows
Access-related information
Business rules
Private conversation context

Therefore, memory retrieval should enforce authorization before semantic ranking.

A safe conceptual order is:

Authentication
     ↓
Authorization
     ↓
Tenant Scope
     ↓
Agent Scope
     ↓
Project Scope
     ↓
Semantic Retrieval

Not:

Vector Search
     ↓
Hope the results belong to the user

This distinction is critical.

An embedding similarity score does not understand your authorization model.

Your application and database controls must enforce it.

Be Careful With Sensitive Memory

A strong memory system should ask:

Does this information actually need to be persisted?

Before storing any sensitive information, consider:

Is persistence necessary?
Who should access it?
How long should it exist?
Can it be minimized?
Can it be anonymized?
Can it be deleted later?

Memory should follow the principle of minimum necessary persistence.

More memory is not automatically better memory.

A Practical Memory Service

Instead of allowing every application component to write directly to TencentDB, create a dedicated memory service.

For example:

AI Agent
   ↓
Memory Service
   ├── Extract
   ├── Validate
   ├── Normalize
   ├── Deduplicate
   ├── Authorize
   ├── Store
   ├── Retrieve
   ├── Rank
   └── Expire
          ↓
      TencentDB

A simplified API could look like:

memory_service.store(
    tenant_id=tenant_id,
    agent_id=agent_id,
    memory_type="procedural",
    scope="project",
    content="Create checkout users through the API.",
    importance=0.90,
    confidence=0.97
)

Retrieval:

memories = memory_service.retrieve(
    tenant_id=tenant_id,
    agent_id=agent_id,
    query="How should checkout users be created?",
    limit=5
)

The application no longer needs to understand every database detail.

That abstraction becomes useful as the system grows.

A Complete Simplified Workflow

Putting everything together:

def process_conversation(conversation, context):
    candidates = extract_memory_candidates(conversation)

    for memory in candidates:

        if not validate_memory(memory):
            continue

        memory = normalize(memory)

        if not authorize_memory(context, memory):
            continue

        related = find_related_memories(
            memory,
            context
        )

        if related:
            reconcile(memory, related)
        else:
            save_to_tencentdb(memory)

Retrieval:

def build_agent_context(query, context):
    candidates = retrieve_candidates(
        query=query,
        tenant_id=context.tenant_id,
        agent_id=context.agent_id,
        project_id=context.project_id
    )

    ranked = rerank(
        candidates,
        query=query
    )

    clean = deduplicate(ranked)

    return fit_context_budget(clean)

This gives you a clean separation:

Memory Write Path
        ↓
Validation → Reconciliation → Persistence

Memory Read Path
        ↓
Filtering → Retrieval → Ranking → Context

What Makes This Different From a Simple Chat History Table?

A chat history table might look like:

CREATE TABLE messages (
    id UUID,
    session_id UUID,
    role VARCHAR(20),
    content TEXT,
    created_at TIMESTAMPTZ
);

That is useful.

But it does not automatically answer:

What should the agent remember?
What is important?
What is current?
What is a preference?
What belongs to this project?
What contradicts previous knowledge?
What should be retrieved?

Agent memory requires another abstraction.

Chat HistoryAgent Memory
Stores messagesStores reusable knowledge
Session-orientedCross-session
ChronologicalRelevance-oriented
Usually rawUsually normalized
Limited lifecycleExplicit lifecycle
Conversation retrievalSemantic + contextual retrieval
Message identityMemory identity

This distinction should remain clear throughout the system.

Your Architecture Decision Checklist

Before implementing TencentDB agent memory storage in a real project, make these decisions explicitly:

□ What counts as a memory?
□ Which memory types exist?
□ Which scopes exist?
□ Who owns each memory?
□ What requires validation?
□ How are duplicates detected?
□ How are conflicts resolved?
□ Which memories expire?
□ Which memories can be deleted?
□ How is semantic retrieval implemented?
□ Which relational fields need indexes?
□ What is the context/token budget?
□ How is tenant isolation enforced?
□ How are retrieval failures measured?
□ How are memory operations monitored?

If these decisions are undefined, adding more database capacity will not solve the fundamental problem.

Test the System With Failure Scenarios

A strategic way to validate your implementation is to deliberately create difficult cases.

Scenario 1: Contradiction

Old:
Project uses Cypress.

New:
Project migrated to Playwright.

Expected:

New memory becomes active.
Old memory becomes superseded.

Scenario 2: Different Projects

Project A → Playwright
Project B → Cypress

Query:

What framework does Project A use?

Expected:

Playwright

Scenario 3: Expired Memory

API version 2
expires_at = yesterday

Expected:

Do not retrieve as active memory.

Scenario 4: Duplicate

Team prefers API test data.
Team prefers creating test data through APIs.

Expected:

One canonical memory.

Scenario 5: Low Confidence

The user might prefer Cypress.

Expected:

Do not treat it as an authoritative preference.

These tests reveal weaknesses much faster than simply checking whether an INSERT statement succeeds.

The Strategic Architecture

A mature system can eventually look like this:

                         ┌──────────────┐
                         │    User      │
                         └──────┬───────┘
                                ↓
                         ┌──────────────┐
                         │   AI Agent   │
                         └──────┬───────┘
                                │
                ┌───────────────┴───────────────┐
                ↓                               ↓
        Memory Write Path                Memory Read Path
                │                               │
        Extract Candidates                   Query
                ↓                               ↓
          Validate                         Authorize
                ↓                               ↓
          Normalize                         Filter
                ↓                               ↓
        Deduplicate                     Vector / SQL Search
                ↓                               ↓
          Reconcile                          Rerank
                ↓                               ↓
           TencentDB                       Deduplicate
                                                ↓
                                         Context Budget
                                                │
                └───────────────┬───────────────┘
                                ↓
                         ┌──────────────┐
                         │     LLM      │
                         └──────────────┘

This architecture demonstrates the real role of the database.

TencentDB is the durable persistence and retrieval foundation.

It is not responsible for deciding everything an agent should remember.

The intelligence around memory belongs in the application architecture.

Internal Links:

External Links

AI Overview Optimization

What is TencentDB agent memory storage?
TencentDB agent memory storage is a structured approach for persisting reusable AI agent information in TencentDB for PostgreSQL so it can be retrieved across sessions using metadata and, where appropriate, semantic vector search.

People Asked Questions

These questions match the article’s informational intent:

What is TencentDB agent memory storage?

TencentDB agent memory storage is an approach for persisting structured AI agent memories using TencentDB for PostgreSQL, allowing useful information to survive beyond an individual conversation or session.

How can TencentDB store AI agent memory?

AI agent memories can be represented as structured PostgreSQL records containing content, memory type, scope, metadata, timestamps, importance, confidence, and potentially vector embeddings.

Can TencentDB be used for vector-based agent memory?

TencentDB for PostgreSQL can support PostgreSQL-based vector workloads, including pgvector-oriented approaches, making it possible to combine relational metadata with semantic retrieval.

What should an AI agent memory record contain?

A useful record can contain an identifier, tenant or user ownership, agent and project scope, memory type, content, confidence, importance, metadata, timestamps, expiration information, and potentially an embedding.

What is the difference between agent memory and chat history?

Chat history preserves conversation messages, while agent memory extracts and persists reusable knowledge such as preferences, project facts, procedures, and experiences.

How does an AI agent retrieve relevant memories?

A retrieval system can combine metadata filtering, keyword or vector search, relevance ranking, freshness, confidence, importance, and deduplication before passing selected memories to the AI model.

Should every AI agent interaction be saved as memory?

No. Saving every interaction creates noisy and potentially stale memory. A better system identifies information with future value and applies validation, scope, importance, and lifecycle rules before persistence.

Can TencentDB agent memory storage work with Redis?

Yes. A hybrid architecture can use Redis for temporary working state or caching while TencentDB handles durable structured memory and related application data.

Conclusion

TencentDB agent memory storage should be treated as a complete memory-management system rather than a simple database table.

The strongest implementations combine structured PostgreSQL data with semantic retrieval, metadata filtering, lifecycle management, validation, deduplication, conflict resolution, authorization, and observability.

The central workflow is:

Conversation
   ↓
Memory Candidate
   ↓
Validation
   ↓
Normalization
   ↓
Reconciliation
   ↓
TencentDB
   ↓
Filtered Retrieval
   ↓
Semantic Ranking
   ↓
Context Selection
   ↓
AI Agent

The strategic lesson is that persistent memory quality depends on the entire lifecycle, not merely on the database technology.

A powerful database cannot rescue a memory system that stores unreliable information, ignores scope, retrieves stale records, or floods the LLM with irrelevant context.

Conversely, a carefully designed memory model can turn PostgreSQL-based infrastructure into a practical foundation for long-term AI agent knowledge.

Final Key Takeaways

  1. TencentDB agent memory storage should store structured memories, not just raw conversations.
  2. Memory type and scope are essential for distinguishing preferences, facts, procedures, experiences, users, and projects.
  3. Metadata filtering and vector search solve different problems and work best together.
  4. Semantic similarity is a retrieval signal, not a guarantee of correctness.
  5. Confidence, importance, freshness, and expiration should influence memory usage.
  6. Duplicate and conflicting memories must be reconciled, not blindly inserted.
  7. Tenant and project isolation must be enforced before memories reach the AI model.
  8. Redis and TencentDB can complement each other when temporary working state and durable memory have different requirements.
  9. Memory retrieval should have a context budget so irrelevant information does not overwhelm the model.
  10. Production memory systems need observability and evaluation, not just database monitoring.
  11. The best memory architecture is task-driven: first determine what the agent needs to know, then design how that knowledge should be stored and retrieved.
  12. The ultimate goal is not to make the agent remember everything. It is to make the agent remember the right things and retrieve them at the right time.

Continue Learning

Explore more expert articles on Mobile Testing, Backend & API, AI & Agentic, AI Tools, n8n, LangChain, CrewAI, MCP Servers, AI Agents, LlamaIndex, Docker, FastAPI, Playwright, Cypress, Test Automation, DevOps, and Software Engineering at www.skakarh.com.

QAPulse by SK delivers expert release analysis, AI engineering insights, enterprise automation strategies, migration guidance, DevOps best practices, and practical testing knowledge to help software professionals build scalable, intelligent, and production-ready software systems.

Advertisement
Found this helpful? Clap to let Shahnawaz know — you can clap up to 50 times.