Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 17 of 28
❮Prev Next❯

Size and Tune PostgreSQL for Vector Workloads

Module 2: Data for AI ⏱ 12 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    Vector search on Azure Database for PostgreSQL is hungry for memory: HNSW indexes are fastest when they fit in RAM, so busy vector workloads usually run on General Purpose or Memory Optimized compute, not Burstable. Raise maintenance_work_mem for index builds, tune m and ef_construction (HNSW) or lists (IVFFlat, built after loading data), and size IOPS with Premium SSD v2. For throughput, reuse connections with psycopg_pool in the app and the built-in PgBouncer on port 6432.

    Simulate it » No Azure account needed

    Exam objective: 2.2.4 Configure compute, memory, and storage resources to support vector workloads. 2.2.6 Implement connection optimization to improve throughput and minimize latency. (Skills measured as of October 7, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Size compute and storage, then turn on PgBouncer Size compute and storage, then turn on PgBouncer.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Vector indexes like memory. Move from <strong>Burstable</strong> to <strong>General Purpose</strong>, which also unlocks PgBouncer.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Vector indexes like memory. Move from Burstable to General Purpose, which also unlocks PgBouncer.
    2. Hundreds of short-lived app connections hurt PostgreSQL. Search pgbouncer and set pgbouncer.enabled to true.
    3. Leave the blade and come back to see the PgBouncer settings. Transaction pooling lends a server connection only for one transaction.
    4. Same host name, port 6432 instead of 5432. That’s the only change in your app.
    5. Server connections drop from hundreds to a steady few dozen, while the app still opens as many as it likes.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    Vector search is fast in testing and crawls in production.

    😊 THE SOLUTION

    Give the index memory, pool connections and size the server for vectors.

    • Index doesn’t fit in memory✓ Memory-optimised compute
    • Too many connections✓ Built-in PgBouncer
    • Slow disk✓ Premium SSD v2 IOPS
    🛠️ Solved with: Vector performance tuning

    Start with a question

    The vector search was fast in testing. Why is it slow now that real users have arrived?

    Think of a busy railway ticket counter. In testing there was one clerk and three customers. On launch day there are 500 people in the queue, every one of them wants a new form printed from scratch, and the clerk’s desk is too small to keep the timetable open.

    That’s what happens to an untuned database. Too little memory to keep the vector index handy, a compute tier that runs out of CPU credits, and an app that opens a brand-new connection for every request. Each of these has a specific fix.

    Explain it like I’m 10

    The technical explanation

    1. Pick the compute tier

    TierWhat it’s forVector workloads
    BurstableDev, test, low steady use; runs on CPU creditsFine for trying pgvector. Long index builds and steady search burn credits. No built-in PgBouncer, no Premium SSD v2
    General PurposeMost production apps, balanced CPU and memoryA good default for moderate vector search
    Memory OptimizedMore RAM per vCoreLarge HNSW indexes that must stay in memory

    The rule of thumb: HNSW is fast when the index lives in memory (shared_buffers plus the OS cache). Check its size with SELECT pg_size_pretty(pg_relation_size('ix_chunks_embedding'));. If it’s bigger than the RAM you can spare, searches hit disk and latency jumps. Moving to Memory Optimized or a larger size is often the real fix, and you can scale compute up or down after creation (with a short restart).

    2. Size storage and IOPS

    Loading millions of embeddings and building indexes is heavy on disk. Premium SSD v2 lets you set capacity, IOPS and throughput separately. A disk under 400 GiB gets a baseline of 3,000 IOPS and 125 MB/s at no extra cost, and you can raise IOPS (up to 80,000 on large enough disks) for a busy load day, then lower it again. The VM size also caps IOPS, so a 2-vCore server can’t use all of an 80,000 IOPS disk. Premium SSD v2 works with General Purpose and Memory Optimized, not Burstable.

    3. Build indexes the smart way

    The Microsoft docs put it simply: load your data first, then build the index. It’s faster and the result is better laid out.

    -- in the session that builds the index
    SET maintenance_work_mem = '4GB';            -- let the HNSW graph fit in memory
    SET max_parallel_maintenance_workers = 7;    -- parallel build
    
    CREATE INDEX CONCURRENTLY ix_chunks_embedding
      ON doc_chunks USING hnsw (embedding vector_cosine_ops)
      WITH (m = 16, ef_construction = 64);
    
    -- watch progress from another session
    SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS pct
    FROM pg_stat_progress_create_index;

    CONCURRENTLY lets reads and writes continue during the build, at the cost of a slower build. Keep maintenance_work_mem within what the server can spare: setting it higher than free memory causes trouble.

    HNSWIVFFlat
    How it worksLayered graph of neighboursk-means clusters (“lists”)
    Build optionsm (default 16), ef_construction (default 64)lists: start with rows/1000 up to 1M rows, sqrt(rows) above
    Query knobhnsw.ef_search (default 40)ivfflat.probes (default 1): start near lists/10
    Build on empty tableYesNo. Load data first, or clusters are meaningless
    Speed vs recallBetterLower, but faster to build and smaller
    MemoryMoreLess

    Higher m and ef_construction give better recall and a bigger, slower-to-build index. Most apps keep the defaults and tune hnsw.ef_search per query instead. If you set ivfflat.probes equal to lists, you’re searching everything and the planner skips the index. Flexible server also offers a DiskANN index through the pg_diskann extension for very large datasets.

    4. Cut connection overhead

    Every new PostgreSQL connection means a TLS handshake, sign-in and a new server process. Two layers of pooling fix it.

    In the app: psycopg_pool. Each app instance keeps a few connections open and lends them out:

    from psycopg_pool import ConnectionPool
    
    pool = ConnectionPool(
        conninfo="host=contoso-pg.postgres.database.azure.com port=6432 dbname=support user=rag-api sslmode=require",
        connection_class=EntraConnection,   # fetches a fresh Entra token per new connection
        min_size=2, max_size=10,
        max_lifetime=3000,                  # recycle connections before tokens and servers get stale
    )
    
    def search(q, tenant):
        with pool.connection() as conn:
            return conn.execute(RETRIEVE_SQL, {"q": q, "tenant": tenant}).fetchall()

    On the server: built-in PgBouncer. When 30 container replicas each hold 10 connections, that’s 300 PostgreSQL processes. PgBouncer sits on the server, accepts up to thousands of client connections on port 6432 and shares a small pool of real connections. Turn it on with the pgbouncer.enabled server parameter (no restart needed); then pgbouncer.pool_mode (default transaction), pgbouncer.default_pool_size and pgbouncer.max_client_conn appear. Your app only changes its port from 5432 to 6432. In transaction mode, session state such as SET (without LOCAL) doesn’t stick between transactions, so use SET LOCAL hnsw.ef_search inside a transaction. If you hit prepared statement errors, set psycopg’s prepare_threshold=None or keep PgBouncer’s max_prepared_statements tracking on.

    Architect level Exact search can be fine, and parallel workers help

    Without an index pgvector does an exact search, with perfect recall. For a table of 50,000 chunks per tenant that might be quick enough, especially if max_parallel_workers_per_gather lets PostgreSQL scan in parallel (look for Workers Launched in EXPLAIN ANALYZE). Approximate indexes earn their cost once tables reach hundreds of thousands of rows or latency targets get tight. Start with EXPLAIN (ANALYZE, BUFFERS): shared hit means pages came from memory, read means disk. A plan full of reads is your hint that memory, not CPU, is the problem.

    Real-world business scenario

    Education

    Wide World Learning (fictional)

    The problem
    A study-help app on a 2-vCore Burstable server stalled every evening when students logged in. CPU credits ran out, the 9 GB HNSW index didn't fit in memory, and 40 container replicas each opened their own connections.
    What they used
    A move to Memory Optimized with Premium SSD v2 (extra IOPS during nightly loads), psycopg_pool in each replica and the built-in PgBouncer on port 6432 in transaction mode.
    Why that choice
    The index now stays in memory, IOPS can be raised only during the load window, and PgBouncer turned hundreds of client connections into a few dozen server connections.
    The result
    Evening search latency became steady, and nightly re-indexing finished within the window instead of running into the morning.

    When to use it and when not to

    ✓ Use it when…

    • Your vector index is growing past what fits in memory on the current size.
    • Many app instances or serverless functions connect to the same server.
    • Load days need extra disk performance for a few hours.

    ✕ Think twice when…

    • Scaling hardware before you've checked the plan. A missing or mismatched index is cheaper to fix.
    • Raising maintenance_work_mem server-wide to a huge value. Set it for the build session.
    • PgBouncer in transaction mode for code that depends on session state, unless you change that code.

    ↔ Alternatives to consider

    • Read replicas to spread search reads away from the primary.
    • Azure Managed Redis to cache frequent answers so many requests never reach PostgreSQL.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    Many instances of a containerized API connect to an Azure Database for PostgreSQL flexible server that runs in the General Purpose tier. The server reaches its connection limit during peak hours. You need to reduce the number of server connections with minimal code changes. What should you do?

    Question 2

    Question 2 of 5

    You plan to create an IVFFlat index on a table that will store 800,000 embeddings. The table is currently empty. When should you create the index?

    Question 3

    Question 3 of 5

    Building an HNSW index on several million vectors takes many hours. The server has unused memory. Which setting should you increase for the session that builds the index?

    Question 4

    Question 4 of 5

    A vector search workload on Azure Database for PostgreSQL is slow. Monitoring shows low CPU usage, and EXPLAIN (ANALYZE, BUFFERS) shows that most index pages are read from disk. The HNSW index is larger than the available memory. Which change is most likely to improve query latency?

    Question 5

    Question 5 of 5

    During a monthly bulk load, an Azure Database for PostgreSQL flexible server is limited by disk IOPS. The storage capacity is sufficient. You need to raise IOPS for the load period without increasing storage size. Which storage option supports this requirement?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner Why isn't Burstable a good choice for a production vector search workload?

    Model answer

    Burstable runs on CPU credits. Vector search and index builds keep the CPU busy for long stretches, so credits run out and the server slows right down. It's also short on memory, and HNSW wants its index in RAM. Burstable is fine for a dev box; production goes on General Purpose or Memory Optimized.

    Interviewer follows up

    Does Burstable support the built-in PgBouncer?

    You

    No. PgBouncer is supported on General Purpose and Memory Optimized only.

    Intermediate How do you speed up building an HNSW index on 5 million rows?

    Model answer

    Load the data first, then build. Raise maintenance_work_mem for the session so the graph fits in memory, and raise max_parallel_maintenance_workers so the build runs in parallel. I watch progress in pg_stat_progress_create_index. If I need it even faster, I can lower ef_construction a bit, accepting slightly lower recall.

    Experienced developer Your API opens a new PostgreSQL connection per request and latency is poor at peak. What do you change?

    Model answer

    I add psycopg_pool in the app so each worker reuses open connections, with a fresh Entra token for each new one. If there are many app instances, I also point them at PgBouncer on port 6432 with transaction pooling, so thousands of client connections share a small number of server connections. With transaction pooling I either keep PgBouncer's prepared statement tracking on or set prepare_threshold to None in psycopg.

    Architecture & design How do you decide between more vCores, more memory and more IOPS?

    Model answer

    I look at the metrics. If CPU is pinned during searches, I add vCores. If the HNSW index is bigger than shared buffers and reads hit disk, memory is the fix, so I move to Memory Optimized. If disk queue depth or IOPS are at the limit during loads, I raise IOPS on Premium SSD v2 without changing size. Connection errors point to pooling, not hardware.

    Quick revision

    Key points

    • Burstable is for dev and test; vector workloads belong on General Purpose or Memory Optimized.
    • HNSW is fastest when the index fits in memory. Memory Optimized gives the most RAM per vCore.
    • Load data first, then build the index, with a higher maintenance_work_mem and parallel workers.
    • HNSW: m (16), ef_construction (64), hnsw.ef_search (40). IVFFlat: lists at build, ivfflat.probes at query.
    • Premium SSD v2 lets you set IOPS and throughput separately from capacity.
    • Reuse connections with psycopg_pool; share them across instances with PgBouncer on port 6432.

    Important terminology

    Compute tiers
    Burstable (cheap, CPU credits, for dev and test), General Purpose (balanced) and Memory Optimized (more RAM per vCore) for flexible server.
    maintenance_work_mem
    The memory PostgreSQL may use for maintenance work such as CREATE INDEX. HNSW builds are much faster when the graph fits in it.
    m and ef_construction
    HNSW build options. m is the maximum connections per node (default 16), ef_construction is the candidate list size while building (default 64).
    lists and probes
    IVFFlat options. lists is the number of clusters set at build time; ivfflat.probes is how many clusters a query searches.
    Premium SSD v2
    Flexible server storage where capacity, IOPS and throughput can be set separately.
    PgBouncer
    A lightweight connection pooler built into flexible server, enabled with pgbouncer.enabled and reached on port 6432.
    psycopg_pool
    The connection pool package for psycopg 3, which keeps open connections ready for reuse inside your app.

    Common mistakes

    • Building an IVFFlat index on an empty table, so its clusters are learned from no data.
    • Running a busy vector workload on Burstable and running out of CPU credits.
    • Pointing an app at port 5432 and expecting PgBouncer pooling.

    Exam tips

    • "Speed up CREATE INDEX for HNSW" = raise maintenance_work_mem (and parallel maintenance workers).
    • "Too many connections from many app instances" = built-in PgBouncer, port 6432.
    • "Raise IOPS without buying more storage" = Premium SSD v2.

    Five quick revision questions

    1. 1.Which port does the built-in PgBouncer use?Show

      6432

    2. 2.Which server parameter turns PgBouncer on?Show

      pgbouncer.enabled

    3. 3.When should you build an IVFFlat index?Show

      After the data is loaded.

    4. 4.Which tier gives the most memory per vCore?Show

      Memory Optimized.

    5. 5.What's the default HNSW m value?Show

      16

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Azure Managed Redis: Caching, Expiration and Invalidation

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.