PostgreSQL & pgvector
psycopg and Entra tokens · vector(n) columns · IVFFlat, HNSW, DiskANN · compute and storage · embeddings and RAG · PgBouncer
By the tools4free.dev team · Last reviewed November 13, 2026
Practice questions for this topic →
Connect and query from Python
Microsoft's Python quickstart for Azure Database for PostgreSQL flexible server shows two authentication methods: Microsoft Entra authentication (the Passwordless tab) and PostgreSQL authentication (the Password tab).
| Microsoft Entra (passwordless) | PostgreSQL (password) | |
|---|---|---|
| Identity | Identities defined in Microsoft Entra ID | Accounts stored in PostgreSQL |
| Python packages in the quickstart | azure-identity (and azure-keyvault-secrets if you use Key Vault) | psycopg, installed as "psycopg[binary]" |
| Server prerequisite | Entra authentication configured, and you are a Microsoft Entra administrator on the server | A PostgreSQL account (the quickstart uses the administrator login and its password) |
| How the password is obtained | credential = DefaultAzureCredential(), then credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token is used as the password | The DBPASSWORD environment variable |
| Upkeep | Tokens have a limited lifetime (24 hours by default): implement a token refresh policy | You manage the rotation of the passwords yourself |
- Connect with
conn = psycopg.connect(conn_string), run SQL withcursor.execute(...), read withcursor.fetchall()and callconn.commit()to persist changes. - Pass values as parameters:
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150)). - The quickstart sets
SSLMODE=requirein the connection settings. - Reuse the credential across calls so you benefit from token caching and avoid extra round trips to the identity provider.
- Network path: a server with private access can only be reached from a resource in the same virtual network; with public access you add your client IP to the server firewall rules.
The quickstart's get_conn.py is demonstration code: it creates DefaultAzureCredential() on every call and has no token refresh. Production code needs both a reused credential and a refresh policy.
Schemas, data types and extensions
- A vector column is typed with its dimension count, for example
embedding vector(3)in the pgvector article orvector(1536)in the semantic-search tutorial. A key such asid bigserial PRIMARY KEYsits beside it. - To index a column it must have dimensions defined; a column declared as plain
vectorcannot be indexed. - You can index a column with up to 2000 dimensions with
ivfflatorhnsw. You can store more than 2000 dimensions but cannot index them; dimensionality reduction is one way to fit the limit. DiskANN (pg_diskann v0.6 and later, with product quantization on) supports up to 16,000 dimensions. - For every text field you search, add a matching vector column and fill it with the embedding of that field's value.
- Partition by a range (for example a date column) so queries that filter on that column read only the relevant partitions; you can index a partitioned table.
Enable the extensions
- Allowlist the extension in the
azure.extensionsserver parameter (portal Parameters pane oraz postgres flexible-server parameter set). - Check with
SHOW azure.extensions;. - Connect to the target database and run
CREATE EXTENSION vector;. Repeat for every database that needs it.
The community calls it pgvector, but the extension and binary are named vector. That is the name you allowlist and create. pg_diskann depends on vector: allow and create vector first, or run CREATE EXTENSION IF NOT EXISTS pg_diskann CASCADE;. The semantic-search tutorial also allowlists and creates azure_ai.
Index types and query tuning
Without an index, pgvector does an exact search (perfect recall, slower). An approximate nearest neighbor (ANN) index trades recall for speed. Load data before you build the index.
| Index | Build and memory | Key options (defaults) | Query-time setting |
|---|---|---|---|
IVFFlat (ivfflat) | Faster build, less memory than HNSW; lower speed-recall tradeoff. Uses k-means lists, so it needs data first | lists (set at create) | ivfflat.probes |
HNSW (hnsw) | Slower build, more memory than IVFFlat; better speed-recall tradeoff; no training step, so it can be built on an empty table | m (16), ef_construction (64) | hnsw.ef_search (40) |
DiskANN (diskann) | Balance of high accuracy and fast build; no training step; Flexible Server only | max_neighbors (32), l_value_ib (50 on the tuning page, 100 on the DiskANN page: the pages differ) | diskann.l_value_is |
| Distance | Operator | Index operator class |
|---|---|---|
| Cosine | <=> | vector_cosine_ops |
| L2 (Euclidean) | <-> | vector_l2_ops |
| Inner product (the operator gives the negative inner product) | <#> | vector_ip_ops |
The query must use the operator that matches the index's operator class, or the planner does not consider the index.
Tuning rules from Microsoft's page
- IVFFlat start points:
lists= rows / 1000 up to 1 million rows and sqrt(rows) above;probes= lists / 10 up to 1 million rows and sqrt(lists) above. - If probes equals the number of lists, every list is searched and the search is exact, so the index is not used by the planner.
- Set probes or ef_search for the connection (
SET ...) or for one transaction (SET LOCAL ...inside a transaction block). - If your vectors are normalized to length 1 (like OpenAI embeddings), consider inner product (
<#>) for best performance. - Start with the query plan:
EXPLAIN (ANALYZE, VERBOSE, BUFFERS). Check whether the query was parallelized, an index was used, the WHERE matches a partial index and unneeded partitions were pruned. max_parallel_workers_per_gathersets the background workers per Gather node; raising it might speed up exact search without an index.- A partial index (for example
... WHERE tier = 'premium') is smaller and faster to search, but queries must use a matching WHERE form. - Check build progress with
pg_stat_progress_create_index(PostgreSQL 12 and newer). - DiskANN: PostgreSQL decides when to use the index;
SET LOCAL enable_seqscan TO OFF;inside a transaction forces it. Raisemaintenance_work_memto speed up the build. - DiskANN product quantization (
product_quantized=true) is labelled Preview on its page; the page ties it to pg_diskann v0.6 and later.
Compute, memory and storage
| Tier | Page's description | Use for |
|---|---|---|
| Burstable | CPU credit model: credits build below baseline and are used above it | Workloads that do not need full CPU continuously. The page calls it not recommended for production; no PgBouncer |
| General Purpose | Balance between CPU and memory with scalable I/O throughput | Most production workloads |
| Memory Optimized | In-memory performance for faster transaction processing and higher concurrency | High-performance, high-concurrency workloads |
- After creation you can change vCores (up or down) and storage size (up only) in seconds. You can only scale storage up, not down.
- For Burstable, monitor
CPU Credits Remainingin Azure Monitor and alert on low credits. Burstable does not qualify for 24/7 support. - Provisioned storage holds database files, temporary files, transaction logs and server logs, and it defines the I/O capacity. The VM size has IOPS limits too, so a server with few vCores might not use all IOPS the disk offers.
- Disk types: Premium SSD and Premium SSD v2.
| Premium SSD v2 | Premium SSD | |
|---|---|---|
| Sizes | Any size from 1 GiB to 64 TiB, adjustable in 1 GiB steps | Dedicated sizes |
| Max disk size | 65,536 GiB | 32,767 GiB |
| Max throughput | 1,200 MB/s | 900 MB/s |
| Max IOPS | 80,000 | 20,000 |
| Host caching | Not supported | - |
| Performance tuning | Capacity, throughput and IOPS adjustable independently at any time | - |
- Disk full: the server switches to read-only at 95 percent usage or when less than 5 GiB is free. Use storage autogrow (for Premium SSD) or scale storage up. Autogrow for Premium SSD v2 is in public preview.
- If the server is read-only because the disk is full, delete data you no longer need after running
SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;. - Monitor
storage_percentageorstorage_usedand alert before the disk fills.
Vector search and RAG
Vector similarity compares embeddings with a distance metric such as Euclidean distance or cosine similarity. The retrieval half of retrieval-augmented generation (RAG) is a nearest-neighbor query over stored embeddings.
- Create a vector column for each searched field (
ALTER TABLE recipes ADD COLUMN embedding vector(1536);). - Generate embeddings with the
azure_aiextension, for exampleazure_openai.create_embeddings('text-embedding-ada-002', ...), and store them. - Generate the embedding for the user's query.
- Search the vector column for the nearest neighbors: the tutorial's search function orders by the cosine distance (
embedding <=> query_embedding) ascending and applies a limit. - Rank further with a relevance or ranking model; without one, rank by decreasing dot product.
- Point
azure_aiat your Azure OpenAI resource withazure_ai.set_setting('azure_openai.endpoint', ...)and the subscription key setting;deployment_nameis the name of the deployment that contains the model. create_embeddingsparameters includebatch_size(default 100, for thetext[]overload),max_attempts(default 1) andretry_delay_ms(default 1000).dimensionsis supported only in text-embedding-3 and later models.- Backfill in chunks: a high
LIMITcan make Azure OpenAI throttle the request and fail the statement halfway through. - Metadata filter: add a WHERE on a metadata column to the similarity query. A partial index with the same WHERE (
WHERE tier = 'premium') serves that filter; partitioning by a range column lets the planner read only the needed partitions. - Basic pgvector SQL:
INSERT ... ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embeddingto upsert;SELECT ... ORDER BY embedding <-> '[3,1,2]' LIMIT 5for the nearest rows.
Connection optimization with PgBouncer
Postgres uses a process-based model for connections, so many idle connections are expensive. Built-in PgBouncer pools them. It runs on the same VM as the server and uses a server connection only inside an open transaction or while a query is active.
| Item | Value |
|---|---|
| Port | 6432 (regular PostgreSQL port is 5432); same host name |
| Enable | Set pgbouncer.enabled to true on the Parameters pane; no server restart needed. The same page also says PgBouncer is enabled by default on port 6432: Microsoft's page is not consistent, so follow the parameter. |
| Tiers | General Purpose and Memory Optimized; not Burstable |
| Default pool mode | transaction |
pgbouncer.default_pool_size | 50 per user/database pair |
pgbouncer.max_client_conn | 5000 |
pgbouncer.query_wait_timeout | 120 seconds |
pgbouncer.server_idle_timeout | 600 seconds |
| Scale | Up to 10,000 connections with low overhead |
| Pooling mode | Server connection is held for |
|---|---|
| Session | The whole client connection |
| Transaction | One transaction (default in the built-in PgBouncer) |
| Statement | One statement; multi-statement transactions are not supported |
- Switch an app by changing the port from 5432 to 6432, test in QA first (Microsoft recommends transaction pooling for most users), then change production.
- Restarts (scale, HA failover, restart) also restart PgBouncer, so applications must re-establish connections. After an HA failover PgBouncer restarts on the new primary and the connection string stays the same.
- Statement pool mode cannot be used with prepared statements. Protocol-level prepared statements in transaction mode need
pgbouncer.max_prepared_statementsabove its default of 0. - PgBouncer is single-threaded. For very many short-lived connections, run several instances behind a load balancer on Azure VMs.
- Alternatives: PgBouncer on the app VM, on VMs behind Azure Load Balancer, as an AKS sidecar (Microsoft publishes a sidecar image in Microsoft container registry) or as a standalone service in AKS. A sidecar per pod multiplies connections to the database on large clusters; for hundreds of pods use a standalone service.
- PgBouncer metrics are disabled by default; enable
metrics.pgbouncer_diagnostics(dynamic, no restart). Admin console: setpgBouncer.stats_users, connect to thepgbouncerdatabase on port 6432 and runSHOW POOLS.
CLI and PowerShell
| Task | Azure CLI | PowerShell |
|---|---|---|
| Allowlist an extension | az postgres flexible-server parameter set --resource-group <resource_group> --server-name <server> --name azure.extensions --value "<extension_name>,<extension_name>" | SHOW azure.extensions; |
| Install pgvector in a database | - | CREATE EXTENSION vector; |
| Install DiskANN with its dependency | - | CREATE EXTENSION IF NOT EXISTS pg_diskann CASCADE; |
| Connect with psycopg | - | conn = psycopg.connect(conn_string) |
| Insert with parameters | - | cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150)) |
| Add an embedding column | - | ALTER TABLE recipes ADD COLUMN embedding vector(1536); |
| Create an IVFFlat cosine index | - | CREATE INDEX t_test_embedding_cosine_idx ON t_test USING ivfflat (embedding vector_cosine_ops) WITH (lists = 5000); |
| Set IVFFlat probes | - | SET ivfflat.probes = 10; |
| Set HNSW candidate list for search | - | SET hnsw.ef_search = 100; |
| Force a DiskANN index scan | - | SET LOCAL enable_seqscan TO OFF; |
| Make a full-disk server writable | - | SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE; |
Exam Tips
Tick each tip once you can answer it without looking.
“Python app must reach Azure Database for PostgreSQL without storing a password” → Microsoft Entra authentication: DefaultAzureCredential, get_token("https://ossrdbms-aad.database.windows.net/.default"), token as the password. Trap: The token lifetime is limited (24 hours by default), so production code needs a token refresh policy. The server also needs Entra authentication configured and you as an Entra admin.
“Install a PostgreSQL driver for the password-based Python quickstart” → psycopg ("psycopg[binary]"). Trap: azure-identity is the package for the passwordless (Entra) path.
“Name to allowlist and create for pgvector” → vector, allowed in azure.extensions, then CREATE EXTENSION vector; in each database. Trap: pgvector is only the community name. Allowlisting alone does not install it; the CREATE is per database.
“Column must be indexable with ivfflat or hnsw” → Declare dimensions, vector(n), with n at most 2000. Trap: A plain vector column or one above 2000 dimensions cannot be indexed; storing it is still allowed.
“Embeddings with more than 2000 dimensions need an index” → DiskANN with product quantization on (pg_diskann v0.6+, up to 16,000 dimensions), or reduce dimensionality. Trap: Product quantization is labelled Preview on its page. ivfflat and hnsw stop at 2000.
“Index with no training step that can be built on an empty table” → HNSW (also DiskANN). Trap: IVFFlat uses k-means lists, so build it after the data is loaded.
“Fastest build and least memory, accepting lower speed-recall” → IVFFlat. Trap: HNSW builds slower and uses more memory but has the better speed-recall tradeoff.
“Cosine search must use the index” → vector_cosine_ops index and the <=> operator in ORDER BY. Trap: <-> is L2 (vector_l2_ops) and <#> is inner product (vector_ip_ops); a mismatch means the index is not considered.
“Better recall from an IVFFlat index at query time” → Raise ivfflat.probes (per connection or SET LOCAL). Trap: More probes cost speed. Probes equal to the list count is an exact search that skips the index.
“Better recall from an HNSW index at query time” → Raise hnsw.ef_search (default 40). Trap: m and ef_construction are build-time options, fixed at CREATE INDEX.
“Query is slow: first step” → Read the plan with EXPLAIN (ANALYZE, VERBOSE, BUFFERS): parallel? index used? partitions pruned?. Trap: Do not add indexes blindly. A partial index is used only when the query's WHERE matches its definition.
“Force a DiskANN index scan in one transaction” → SET LOCAL enable_seqscan TO OFF; inside a transaction. Trap: A session-level SET affects later statements; SET LOCAL ends at COMMIT or ROLLBACK.
“Server went read-only because the disk is almost full (95 percent or under 5 GiB free)” → Scale storage up (storage can only grow) or enable autogrow, delete data after SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;. Trap: You cannot scale storage down, and Premium SSD v2 autogrow is public preview.
“Dev or test server with idle periods; risk of CPU credits running out” → Burstable tier; watch CPU Credits Remaining. Trap: Page: not recommended for production. Burstable has no built-in PgBouncer.
“Tune IOPS, throughput and size of the disk independently, any size from 1 GiB” → Premium SSD v2. Trap: Premium SSD has dedicated sizes; v2 has no host caching.
“Too many idle or short-lived connections hurt the server” → Built-in PgBouncer: pgbouncer.enabled = true, connect on port 6432. Trap: Port 5432 is the regular PostgreSQL port, not PgBouncer. PgBouncer is not supported on Burstable. Statement mode cannot be used with prepared statements.
“Backfill thousands of embeddings with azure_openai.create_embeddings” → Update in chunks with a modest LIMIT and repeat until no rows remain. Trap: A very large batch can be throttled by Azure OpenAI and fail halfway through.
“Similarity search limited to one customer tier” → WHERE on the metadata column, backed by a partial index with the same WHERE or by partitioning. Trap: A WHERE form that differs from the partial index definition (for example LIKE) means the index is not used.
Sources
- Connect and query with Python (flexible server)
- Vector search with pgvector
- Optimize performance when using pgvector
- Enable and use DiskANN
- Allow extensions
- Compute options
- Storage options
- PgBouncer in Azure Database for PostgreSQL
- Connection pooling strategy using PgBouncer
- Create a semantic search with Azure OpenAI
- Generate vector embeddings with Azure OpenAI
Checked against Microsoft Learn on November 13, 2026.