What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
PostgreSQL can be an AI agent’s memory store when the application needs relational records, metadata, permissions, and embeddings queried together. With the pgvector extension, the same database can run vector-similarity searches, ordinary SQL filters, and PostgreSQL full-text search. That combination is often simpler than splitting memory across separate systems, but it is not a universal performance win: the right choice depends on collection size, latency and recall targets, update patterns, and operational capacity.
What does it mean for PostgreSQL to be an AI agent’s memory store?
Agent memory is the information an agent may need after the current model context is gone. It can include conversation summaries, user preferences, tool results, documents, tasks, and changing facts. A useful memory system stores more than text: each item normally needs an owner or tenant, timestamps, source, permissions, lifecycle state, and an embedding that represents its meaning.
PostgreSQL can keep those fields in normal tables while storing an embedding in a vector column. A retrieval query can then find semantically similar rows and apply SQL predicates such as tenant, document type, authorization scope, or time range before the application sends the selected context to the model. This data locality is the central architectural reason to consider PostgreSQL.
Why is keeping vectors beside relational data useful?
The advantage is not that PostgreSQL automatically beats a dedicated vector service. It is that one transactional system can answer a compound question: “Find memories similar to this request, but only for this customer, project, language, and validity period.”
Popular on Amazon
- 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
- 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
- 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
- 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
- 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
- Joins remain ordinary SQL. Memories can join to users, projects, documents, billing records, or access-control tables instead of being copied into a second system.
- Metadata filters are first-class. Exact conditions such as
tenant_id,source, status, and dates are evaluated with SQL rather than approximated through semantic similarity. - Writes can be coordinated. A message, its extracted facts, and the embedding job’s status can be represented in related rows and updated with normal database transactions.
- Hybrid retrieval is available. PostgreSQL full-text search can handle names, identifiers, and exact terms while pgvector handles conceptual similarity; the application can combine both result sets.
- Existing operations may be reused. Teams already running PostgreSQL may avoid adding another database, backup process, credential set, and monitoring surface.
AWS describes this pattern for Aurora PostgreSQL with pgvector: “You can combine the vector search with queries over domain-specific data that is available in the same PostgreSQL instance.” That is an architectural capability, not evidence that a particular managed service is the fastest or least expensive option.
How does pgvector search work?
After installing the extension, a table can hold fixed-dimension vectors and queries can order rows by a distance operator. The pgvector documentation states: “By default, pgvector performs exact nearest neighbor search, which provides perfect recall.” Exact search scans the relevant table (or filtered subset) and returns the mathematically nearest rows, but scan cost grows with the amount of data.
For larger collections, pgvector provides approximate nearest-neighbor indexes. They examine a smaller candidate set to reduce latency, which introduces a recall trade-off that must be measured for the application’s workload.
Free tools Windows power users keep installed
One-click scans. No signup required.
| Mode | What it does | Main trade-off | When to consider it |
|---|---|---|---|
| Exact, no vector index | Scans rows and computes distances directly | Predictable perfect recall, but scan time and compute increase with table size | Small or moderately sized tables, strict recall requirements, or a baseline for comparison |
| HNSW | Builds a graph for approximate nearest-neighbor search | Usually a stronger speed/recall trade-off than IVFFlat, but slower builds and higher memory use | Latency-sensitive retrieval where the index can fit the memory and update costs are acceptable |
| IVFFlat | Partitions vectors into lists and searches selected lists | Typically lighter to build than HNSW, but recall depends heavily on list and probe settings | Workloads that favor simpler or less memory-intensive indexing and can tune probes |
These are design options, not universal rankings. The pgvector project documents both HNSW and IVFFlat as approximate methods, while EnterpriseDB recommends beginning without an index when exact scans meet the required latency. Its row-count guidance is a starting point, not a guaranteed cutoff for every hardware and query shape.
What does a practical agent-memory schema look like?
Start with durable metadata and an embedding column. The dimension must match the embedding model, and changing models generally requires a migration or a second vector column.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE agent_memories (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL,
conversation_id bigint,
content text NOT NULL,
memory_type text NOT NULL,
source text,
embedding vector(1536),
created_at timestamptz NOT NULL DEFAULT now(),
valid_from timestamptz,
valid_to timestamptz,
metadata jsonb NOT NULL DEFAULT '{}'::jsonb
);
The dimension value in this example is illustrative; use the dimension produced by the selected model. pgvector’s README gives a storage formula of 4 * dimensions + 8 bytes for each full-precision vector, before row, alignment, table, and index overhead. That formula helps estimate storage but says nothing by itself about query speed.
Also popular on Amazon
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
For facts that change, avoid overwriting the only copy. Store a new version with validity timestamps and retain the old row. The OpenAI temporal-agent example demonstrates this temporal-validity and non-destructive-history pattern. At retrieval time, filter for facts valid at the question’s reference time, or explicitly ask for historical versions.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →How do you retrieve memories with SQL?
Generate an embedding for the incoming query with the same vector space used for stored memories, then combine distance ordering with mandatory relational filters. A cosine-distance query can look like this:
SELECT id, content, memory_type, metadata,
embedding <=> $1 AS distance
FROM agent_memories
WHERE tenant_id = $2
AND (valid_to IS NULL OR valid_to > $3)
AND valid_from <= $3
ORDER BY embedding <=> $1
LIMIT 8;
Here, $1 is the query vector, $2 identifies the tenant, and $3 is the time at which the fact must be valid. Keep authorization predicates in the SQL path rather than asking the language model to decide which rows it may see. If a row must never be exposed to a tenant, it should be excluded before prompt construction.
For an agent, retrieval is only half the design. Add policies for what becomes durable memory, deduplicate near-identical entries, attach provenance, and provide a deletion or correction path. A database that stores every message forever can create stale or contradictory context even if vector search itself is working correctly.
How do hybrid vector and full-text search work?
Vector similarity is good at paraphrases and concepts; lexical search is better for exact product names, error codes, account numbers, and quoted phrases. PostgreSQL can maintain a full-text representation alongside the embedding and combine the two candidate sets.
Recommended Free Tools
ALTER TABLE agent_memories
ADD COLUMN search_document tsvector;
CREATE INDEX agent_memories_search_idx
ON agent_memories USING gin (search_document);
An application can run a full-text query with websearch_to_tsquery or another PostgreSQL text-search function, run a vector query, and merge or rerank the candidates. Another approach is to use a reciprocal-rank or weighted score in application code. The correct weighting depends on whether exact identifiers or semantic matches are more important; do not assume one score works for every agent.
Also popular on Amazon
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Hybrid retrieval also gives a safer fallback. If an embedding model misses a rare token, the lexical result can still surface it. Conversely, semantic retrieval can find a paraphrased explanation when no exact term appears.
When should you add an HNSW or IVFFlat index?
Add an approximate index only after measuring whether exact search fails the required latency or resource budget. Keep exact sequential-scan results as a recall reference, then compare each index and setting against that reference on representative queries.
- Capture a workload. Include short and long prompts, common and rare memories, tenant filters, time predicates, and realistic concurrent traffic.
- Measure the exact baseline. Record latency, returned-row quality, CPU, memory, and the effect of filtering. This is the reference for recall, not merely a development convenience.
- Build one approximate index. HNSW generally favors recall and query speed at the cost of build time and memory; IVFFlat has different partition and probe trade-offs. Build it with enough representative data for its structure to be meaningful.
- Tune query candidates. For HNSW, pgvector documents a default
hnsw.ef_searchvalue of 40. Raising it can improve recall while increasing work per query. Test the setting with the actual filters and concurrency. - Check filtered results. An index may find many close vectors that fail a tenant or time predicate, leaving fewer than the requested number of rows. pgvector’s iterative scans can help continue searching when filtering would otherwise truncate the result set.
- Recheck after writes. Inserts, updates, and deletes alter index behavior and table maintenance needs. Repeat the comparison after the expected churn, not just on a freshly loaded table.
HNSW and IVFFlat parameters should be treated as workload configuration. Hardware, vector dimensionality, filter selectivity, concurrency, and update frequency can change the best choice.
What operational issues matter in production?
Vector search does not remove normal PostgreSQL responsibilities. Plan backups, replication, connection management, schema migrations, observability, and access controls alongside the retrieval design.
- Memory budget: HNSW indexes can require substantial memory during construction and operation. Check whether the index and hot table data fit the available memory; swapping can erase latency gains.
- Build windows: Large index builds consume resources and can take longer than expected. Schedule them with the ingestion pattern and deployment process in mind.
- Vacuum and dead tuples: Update/delete-heavy memory tables need routine vacuuming. Dead tuples can increase storage and interfere with the number of useful filtered results.
- Embedding consistency: Record the model name, version, dimension, and preprocessing assumptions. Mixing incompatible vector spaces makes distance rankings meaningless.
- Freshness: Separate newly written memories from memories whose embeddings are still pending. An agent should not silently treat an unembedded row as absent.
- Deletion and privacy: Define how user deletion requests remove source text, metadata, embeddings, and derived summaries. Backups and replicas need a matching retention policy.
- Observability: Track query latency, candidate counts, empty-result rates, filter selectivity, index size, vacuum lag, and retrieval quality samples. A low database latency is not useful if the selected context is irrelevant.
Can managed PostgreSQL reduce the operational burden?
Managed PostgreSQL can provide automated infrastructure, backups, and service-level tooling while retaining SQL and pgvector capabilities. AWS documents Aurora PostgreSQL with pgvector as supporting both exact and approximate nearest-neighbor search and combining vectors with domain data. Treat that as one deployment example, not a recommendation or a price comparison.
Before choosing a managed offering, verify the PostgreSQL major version, whether the required pgvector version is supported, available index methods, extension upgrade process, parameter controls, storage and I/O pricing, backup behavior, and regional availability. Managed service terms and costs change independently of the database extension, so check the provider’s current documentation for the intended region and edition.
Also popular on Amazon
- Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
- Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
- 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
- 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
- Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
Are dedicated vector databases necessary, or is pgvector enough for most AI apps?
Neither answer is universal. pgvector is a strong fit when relational joins, permissions, metadata filters, transactions, and hybrid search are central, and when measured vector latency and scale fit the PostgreSQL deployment. A dedicated vector system becomes more compelling when vector retrieval dominates the workload, the collection or concurrency exceeds the database’s tested envelope, or specialized distribution and indexing controls materially improve the required service level.
Compare systems using the same embeddings, filters, query mix, concurrency, and recall target. Include operational work: index builds, memory requirements, ingestion lag, updates and deletes, backups, incident recovery, and the number of systems developers must operate. Do not select a database from a generic “millions of vectors” claim; the available data contains no independent benchmark establishing a universal PostgreSQL threshold or speed advantage.
What decision checklist should an AI team use?
PostgreSQL is usually the practical first candidate when most answers below are “yes.” A “no” does not disqualify it, but it identifies what must be benchmarked or isolated.
- Do memory rows need joins to tenant, user, document, or authorization data?
- Can exact SQL filters remove most unauthorized or irrelevant rows before context assembly?
- Does the application need lexical and semantic retrieval together?
- Can exact search meet the latency target at the expected collection size and concurrency?
- If not, can HNSW or IVFFlat meet recall and latency targets within the memory budget?
- Are writes, updates, deletes, vacuuming, and index rebuilds compatible with the ingestion pattern?
- Can the team operate PostgreSQL reliably, or would a managed service provide the needed controls?
- Would a dedicated vector service demonstrably improve a measured requirement enough to justify another system?
The outcome should be a workload result, not a slogan. Keep an exact-search test path, sample real agent queries, and revisit the choice as memory volume and retention policy change.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.FAQ
How much storage does one embedding require in PostgreSQL?
For a full-precision vector, pgvector documents the raw storage formula 4 * dimensions + 8 bytes. Total database usage is higher because rows, indexes, alignment, metadata, and replicas also consume space. Estimate with the actual dimension and row count, then validate against table and index sizes after loading representative data.
Should every conversation message become a long-term memory?
No. Persisting every message can create stale, repetitive, or conflicting retrieval results. Use a memory policy that selects durable facts, summaries, decisions, or user preferences, and retain provenance so an incorrect memory can be corrected or removed.
Also popular on Amazon
- 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
- 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
- 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
- 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
- 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
How do I migrate memories when the embedding model changes?
Store the embedding model and dimension with each memory, then backfill a new column or versioned table rather than mixing vectors from incompatible spaces. During migration, query the new representation first and keep the old one available until quality and latency checks show that it can be retired.
Can PostgreSQL enforce tenant isolation for agent memories?
Yes, SQL predicates can scope retrieval by tenant, and PostgreSQL row-level security can enforce policies at the database boundary. Configure and test those policies independently of semantic ranking; similarity search should never be the mechanism that decides authorization.
What is the safest way to test approximate recall?
Keep an exact-search result set for the same query and filters, then compare approximate results using a representative labeled or reviewed query sample. Increase candidate settings or change the index only when the measured recall, latency, and resource costs match the application’s requirements.
Frequently Asked Questions
How much storage does one embedding require in PostgreSQL?
For a full-precision vector, pgvector documents the raw storage formula 4 * dimensions + 8 bytes. Total database usage is higher because rows, indexes, alignment, metadata, and replicas also consume space. Estimate with the actual dimension and row count, then validate against table and index sizes after loading representative data.
Should every conversation message become a long-term memory?
No. Persisting every message can create stale, repetitive, or conflicting retrieval results. Use a memory policy that selects durable facts, summaries, decisions, or user preferences, and retain provenance so an incorrect memory can be corrected or removed.
How do I migrate memories when the embedding model changes?
Store the embedding model and dimension with each memory, then backfill a new column or versioned table rather than mixing vectors from incompatible spaces. During migration, query the new representation first and keep the old one available until quality and latency checks show that it can be retired.
Can PostgreSQL enforce tenant isolation for agent memories?
Yes, SQL predicates can scope retrieval by tenant, and PostgreSQL row-level security can enforce policies at the database boundary. Configure and test those policies independently of semantic ranking; similarity search should never be the mechanism that decides authorization.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsWhat is the safest way to test approximate recall?
Keep an exact-search result set for the same query and filters, then compare approximate results using a representative labeled or reviewed query sample. Increase candidate settings or change the index only when the measured recall, latency, and resource costs match the application’s requirements.

