Skip to content
Vector database engineering on Kubernetes · Chapter 9 of 20 Day 8: Performance – a rush at the lending desk

Day 8: Performance – a rush at the lending desk

Goal: measure throughput and response times (p50, p95, p99) with your own load generator, find the bottleneck, show the influence of batch size when ingesting, and measure on a public dataset with a ready-made ground truth what quantization costs and gains · Duration: about 150 min · Prerequisite: Day 0 to Day 7

State before this chapter

Three Qdrant pods are running, one each on vdb2, vdb3 and vdb4. After Day 7 there are two collections.

# on vdb1
kubectl -n qdrant get pods -o wide

Expected (your IPs and ages will differ):

NAME       READY   STATUS    RESTARTS   AGE   IP           NODE   NOMINATED NODE   READINESS GATES
qdrant-0   1/1     Running   0          10h   10.42.1.34   vdb2   <none>           <none>
qdrant-1   1/1     Running   0          9h    10.42.3.21   vdb4   <none>           <none>
qdrant-2   1/1     Running   0          10h   10.42.2.6    vdb3   <none>           <none>
# on vdb1
curl -s http://10.43.151.237:6333/collections

Expected:

{"result":{"collections":[{"name":"doku"},{"name":"verteilt"}]},"status":"ok","time":0.000046478}

doku has 13,220 points with 768 dimensions, one shard with two copies and the HNSW index from Day 4 (m 16, ef_construct 100). Wherever the text says 10.43.151.237, insert the address of your Qdrant Service; for the pod IPs, your values from kubectl get pods -o wide.

Introduction

So far you have asked individual questions and measured the time of one answer. In operation, the questions come simultaneously – from many users, from a RAG application with several workers, from a batch job. Then other numbers count: how many requests per second can the cluster handle? How long does the slowest of a hundred users wait? And where is the bottleneck – in Qdrant, in the network, or in the program doing the measuring?

Then there is the other direction: ingesting data. An index with a million vectors is not built in seconds, and while it is being built, the same CPU is also working for search.

Today you will learn:

  • to write a load generator that measures throughput and p50, p95, p99,
  • to recognize when the load generator itself is the bottleneck,
  • why batch size changes ingestion throughput by more than a factor of twenty,
  • to measure recall and response time with glove-100 – 1.18 million vectors and a ready-made ground truth,
  • what scalar quantization costs in recall and what rescore is for,
  • why search becomes slower while data is being ingested.

Background

The picture of the day: a rush at the lending desk

Saturday morning at the city library. There is a queue in front of the lending desk.

  • How many readers per minute the desk serves is the throughput.
  • How long a reader waits from the question to having the book in hand is the response time (latency).
  • The median (p50) is the reader in the middle: half wait less, half wait longer. The p99 is the slowest of a hundred – the one who complains.
  • More counters (parallelism) serve more readers per minute – until the librarians behind the desk (the CPU) are all busy. After that, the queue only gets longer.
  • Whoever measures the waiting time must not get in the way: a counter who writes down every reader individually and blocks the door while doing so is measuring himself.
  • New books are delivered in crates. A crate with a thousand books is shelved faster than a thousand individual deliveries (batch size). And while the library is being rearranged at night (the optimizer builds the index), there are fewer staff at the desk.
  • Quantization is the paperback edition: smaller, faster to leaf through, slightly less precise. Anyone who wants to know exactly looks it up in the hardcover edition at the end (rescore).

The terms

Term Meaning In the picture
Throughput (QPS) requests per second that the cluster answers readers per minute at the desk
Latency time from request to answer, measured at the client a reader’s waiting time
p50, p95, p99 the value below which 50, 95 or 99 percent of all measurements lie middle, almost all, the slowest of a hundred
Parallelism how many requests are in flight at the same time number of open counters
Closed load generator each reader asks the next question only after the answer reader who goes back to the end of the queue
Batch size points per write request books per crate
Ground truth the exactly correct neighbors of each test question the catalog that is definitely right
Scalar quantization each vector component as 1 byte instead of 4 bytes paperback edition
rescore re-evaluate the best candidates with the original vectors look it up in the hardcover edition

Remember: a performance figure without parallelism, percentile, dataset and hardware is not a figure. “450 requests per second” means nothing – “455 requests/s with 16 parallel readers, p99 70 ms, 13,220 vectors with 768 dimensions” means something.

Drill 1: The load generator

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: a program that searches with fixed parallelism and outputs throughput and percentiles – and a first measurement with a single reader.

Step 1 – create the working folder.

# on vdb1
mkdir -p ~/labor/tag08
# on vdb1
cd ~/labor/tag08

Step 2 – write the load generator. The program asks the 100 test questions from Day 1 in turn until ANZAHL requests have been answered. PARALLEL threads work at the same time; each one asks its next question only when the last one has been answered. This is a closed load generator: it never generates more load than the server works off.

# on vdb1
nano last.py
~/labor/tag08/last.py new file
"""Lastgenerator: schickt Suchanfragen mit fester Parallelität und misst p50, p95 und p99."""
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor

import numpy as np
from qdrant_client import QdrantClient, models

QDRANT, COLLECTION, FRAGEN = sys.argv[1], sys.argv[2], sys.argv[3]
PARALLEL, ANZAHL = int(sys.argv[4]), int(sys.argv[5])
EF = int(sys.argv[6]) if len(sys.argv) > 6 else None   # hnsw_ef, ohne Angabe = Standard

fragen = np.load(FRAGEN)
parameter = models.SearchParams(hnsw_ef=EF)
lokal = threading.local()          # jeder Thread bekommt eine eigene Verbindung


def anfrage(nummer):
    if not hasattr(lokal, "client"):
        lokal.client = QdrantClient(url=QDRANT, timeout=30)
    vektor = fragen[nummer % len(fragen)].tolist()
    beginn = time.perf_counter()
    try:
        lokal.client.query_points(COLLECTION, query=vektor, limit=10, search_params=parameter)
        return (time.perf_counter() - beginn) * 1000, False
    except Exception:
        return (time.perf_counter() - beginn) * 1000, True


start = time.perf_counter()
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
    ergebnisse = list(pool.map(anfrage, range(ANZAHL)))
dauer = time.perf_counter() - start

zeiten = np.array([z for z, fehler in ergebnisse])
fehler = sum(1 for z, f in ergebnisse if f)
p50, p95, p99 = np.percentile(zeiten, [50, 95, 99])
print(f"parallel {PARALLEL} · {ANZAHL} Anfragen in {dauer:.1f} s · {ANZAHL / dauer:.0f} Anfragen/s"
      f" · p50 {p50:.1f} ms · p95 {p95:.1f} ms · p99 {p99:.1f} ms · max {zeiten.max():.1f} ms"
      f" · Fehler {fehler}")
Line Meaning
sys.argv[1] to [5] Qdrant address, collection, file with questions, parallelism, number of requests
sys.argv[6] optional hnsw_ef for each search
threading.local() each thread keeps its own connection instead of sharing one
fragen[nummer % len(fragen)] the questions in turn: request 100 is question 0 again
ThreadPoolExecutor(max_workers=PARALLEL) exactly PARALLEL threads work off the requests
np.percentile(zeiten, [50, 95, 99]) the three percentiles over all measured times
ANZAHL / dauer throughput: answered requests per second

The program measures the time on vdb1. It includes converting the vector to JSON, the trip over the network and through the Service, the search in Qdrant and the way back. That is exactly what an application experiences.

Step 3 – measure with one reader.

# on vdb1
~/werkbank/bin/python last.py http://10.43.151.237:6333 doku ../tag01/fragen.npy 1 1000
Setting Value Meaning
Qdrant http://10.43.151.237:6333 the Service, distributed across all three pods
Collection doku 13,220 vectors, 768 dimensions
Questions ../tag01/fragen.npy the 100 test questions from Day 1
Parallelism 1 one reader, one request after another
Count 1000 each question ten times

Expected (your numbers will differ):

parallel 1 · 1000 Anfragen in 17.3 s · 58 Anfragen/s · p50 10.7 ms · p95 65.3 ms · p99 142.2 ms · max 236.6 ms · Fehler 0

Step 4 – the same command once more right away. Write down beforehand what you expect.

# on vdb1
~/werkbank/bin/python last.py http://10.43.151.237:6333 doku ../tag01/fragen.npy 1 1000

Expected:

parallel 1 · 1000 Anfragen in 12.1 s · 83 Anfragen/s · p50 10.9 ms · p95 17.0 ms · p99 20.8 ms · max 134.2 ms · Fehler 0

What you see:

Value 1st run 2nd run Meaning
p50 10.7 ms 10.9 ms the typical reader – practically the same
p95 65.3 ms 17.0 ms the first run had a slow tail
p99 142.2 ms 20.8 ms seven times as high in the first run
Throughput 58/s 83/s with one reader simply 1000 ÷ sum of all waiting times

The first run hit cold caches: pages of the collection that nobody had read for a long time first had to be brought back into memory, plus the connection setup. The median showed none of this – only the percentiles at the edge. Therefore: run every measurement once to warm up and don’t count it.

Remember: the median tells you about the typical reader, p99 about the dissatisfied one. An outlier in the first run is usually the cold start – warm up first, then measure.

Save your progress? Sign up for free

Drill 2: Opening more counters

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: a curve of parallelism, throughput and p99 – and a suspicion.

With more parallel readers, throughput should rise until Qdrant is fully loaded. Measure four levels with 2000 requests each.

# on vdb1
~/werkbank/bin/python last.py http://10.43.151.237:6333 doku ../tag01/fragen.npy 1 2000

Expected:

parallel 1 · 2000 Anfragen in 24.1 s · 83 Anfragen/s · p50 11.1 ms · p95 17.3 ms · p99 24.2 ms · max 97.4 ms · Fehler 0

Repeat the command with 4, 16 and 64 instead of the 1.

Expected (all four runs):

Parallelism Requests/s p50 p95 p99 max
1 83 11.1 ms 17.3 ms 24.2 ms 97.4 ms
4 138 23.5 ms 47.5 ms 135.3 ms 357.4 ms
16 133 95.7 ms 211.4 ms 283.3 ms 432.6 ms
64 96 340.7 ms 839.7 ms 1174.5 ms 3469.9 ms

What you see: at 4 readers it tops out: about 135 requests per second, no matter how many readers are waiting. From then on only the waiting time grows – with 64 readers even the median is at 341 ms, and throughput actually drops. This is the typical picture of saturation: the queue gets longer, the desk does not get faster.

But who is saturated? Before you tweak Qdrant, take a look.

Step 1 – generate load and measure at the same time. You need two terminals on vdb1. In the first, start a longer run with 16 readers:

# on vdb1, Terminal 1
~/werkbank/bin/python last.py http://10.43.151.237:6333 doku ../tag01/fragen.npy 16 4000

Step 2 – in the second terminal, while terminal 1 is running, look at the pods.

# on vdb1, Terminal 2
kubectl -n qdrant top pods

Expected:

NAME       CPU(cores)   MEMORY(bytes)   
qdrant-0   361m         304Mi           
qdrant-1   188m         215Mi           
qdrant-2   194m         166Mi           

Together not even one core. vdb2 alone has eight.

Step 3 – look at the load generator itself.

# on vdb1, Terminal 2
top -b -n1
  • -b writes the output as text instead of an interactive display.
  • -n1 only one round, then exit.

Expected (excerpt – the process lines):

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
2281897 ubuntu    20   0 2905528 138432  28388 S 100.0   1.1   0:34.69 python
 509717 root      20   0 2531800 886860 190560 S  14.3   6.9      9,08 k3s-ser+

Expected in terminal 1 when the run has finished:

parallel 16 · 4000 Anfragen in 27.9 s · 143 Anfragen/s · p50 95.6 ms · p95 205.9 ms · p99 271.1 ms · max 395.8 ms · Fehler 0

What you see: the Python process is at exactly 100 % – one full core. Python only ever executes Python code in one thread at a time (the Global Interpreter Lock, GIL). The 16 threads are therefore not waiting for Qdrant, but for each other: each one has to convert its vector to JSON and read the response, and that can only happen one after the other. You measured the load generator, not the database.

Remember: before you certify a limit for a database, check the load generator. If the client is at 100 % of one core and the server is almost idle, you are measuring the counter at the door.

Save your progress? Sign up for free

Drill 3: Readers as separate processes

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: a load generator that no longer holds vdb1 back, and the real curve of Qdrant.

Step 1 – write the load generator with processes. Instead of threads, the program starts PARALLEL processes. Each has its own Python interpreter and therefore its own GIL. Each process handles every PARALLEL-th request in sequence and returns its times at the end.

# on vdb1
nano last-prozesse.py
~/labor/tag08/last-prozesse.py new file
"""Lastgenerator mit Prozessen statt Threads: jeder Prozess ist ein eigener Leser mit eigenem Python."""
import sys
import time
from multiprocessing import Pool

import numpy as np
from qdrant_client import QdrantClient, models

QDRANT, COLLECTION, FRAGEN = sys.argv[1], sys.argv[2], sys.argv[3]
PARALLEL, ANZAHL = int(sys.argv[4]), int(sys.argv[5])
EF = int(sys.argv[6]) if len(sys.argv) > 6 else None   # hnsw_ef, ohne Angabe = Standard


def leser(nummer):
    """Ein Prozess: schickt seine Anfragen nacheinander und gibt die Zeiten zurück."""
    fragen = np.load(FRAGEN)
    client = QdrantClient(url=QDRANT, timeout=30)
    parameter = models.SearchParams(hnsw_ef=EF)
    zeiten, fehler = [], 0
    for i in range(nummer, ANZAHL, PARALLEL):
        beginn = time.perf_counter()
        try:
            client.query_points(COLLECTION, query=fragen[i % len(fragen)].tolist(), limit=10,
                                search_params=parameter)
        except Exception:
            fehler += 1
        zeiten.append((time.perf_counter() - beginn) * 1000)
    return zeiten, fehler


if __name__ == "__main__":
    start = time.perf_counter()
    with Pool(PARALLEL) as pool:
        ergebnisse = pool.map(leser, range(PARALLEL))
    dauer = time.perf_counter() - start
    zeiten = np.concatenate([z for z, f in ergebnisse])
    fehler = sum(f for z, f in ergebnisse)
    p50, p95, p99 = np.percentile(zeiten, [50, 95, 99])
    print(f"parallel {PARALLEL} (Prozesse) · {ANZAHL} Anfragen in {dauer:.1f} s"
          f" · {ANZAHL / dauer:.0f} Anfragen/s · p50 {p50:.1f} ms · p95 {p95:.1f} ms"
          f" · p99 {p99:.1f} ms · max {zeiten.max():.1f} ms · Fehler {fehler}")
Line Meaning
Pool(PARALLEL) starts PARALLEL worker processes
pool.map(leser, range(PARALLEL)) each process gets a number from 0 to PARALLEL - 1
range(nummer, ANZAHL, PARALLEL) process 0 takes requests 0, 16, 32 …, process 1 takes 1, 17, 33 …
np.concatenate(…) merge all times of all processes into one list
if __name__ == "__main__": mandatory with multiprocessing: the worker processes reload the file and must not start processes themselves while doing so

Step 2 – measure, starting with one reader.

# on vdb1
~/werkbank/bin/python last-prozesse.py http://10.43.151.237:6333 doku ../tag01/fragen.npy 1 4000

Expected:

parallel 1 (Prozesse) · 4000 Anfragen in 54.4 s · 73 Anfragen/s · p50 13.0 ms · p95 18.0 ms · p99 22.3 ms · max 115.0 ms · Fehler 0

Repeat the command with 4 and 8 readers and 4000 requests, then with 16 and 32 readers and 8000 requests.

Expected (all five runs):

Processes Requests/s p50 p95 p99 max
1 73 13.0 ms 18.0 ms 22.3 ms 115.0 ms
4 204 16.3 ms 26.9 ms 35.5 ms 254.0 ms
8 364 17.6 ms 33.1 ms 44.1 ms 79.1 ms
16 455 29.0 ms 53.7 ms 69.5 ms 110.4 ms
32 564 41.0 ms 87.9 ms 121.8 ms 221.6 ms

What you see: with 16 readers, Qdrant answers more than three times as many requests as before, with a quarter of the waiting time. Up to 8 readers, throughput rises almost in lockstep, and the median stays at 13 to 18 ms. After that, throughput rises more slowly and waiting time faster – this is where the queue begins.

Step 3 – who is working now? In terminal 1, start a longer run:

# on vdb1, Terminal 1
~/werkbank/bin/python last-prozesse.py http://10.43.151.237:6333 doku ../tag01/fragen.npy 16 12000

In terminal 2, while it is running:

# on vdb1, Terminal 2
kubectl -n qdrant top pods

Expected:

NAME       CPU(cores)   MEMORY(bytes)   
qdrant-0   3624m        317Mi           
qdrant-1   631m         219Mi           
qdrant-2   523m         167Mi           
# on vdb1, Terminal 2
kubectl top nodes

Expected:

NAME   CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)   
vdb1   3246m        27%      2341Mi          18%         
vdb2   3365m        42%      1308Mi          7%          
vdb3   578m         28%      791Mi           9%          
vdb4   1156m        57%      998Mi           12%         

Expected in terminal 1:

parallel 16 (Prozesse) · 12000 Anfragen in 24.1 s · 497 Anfragen/s · p50 28.1 ms · p95 50.2 ms · p99 66.0 ms · max 110.3 ms · Fehler 0

What you see: now Qdrant is working: qdrant-0 uses 3.6 cores. The load is unevenly distributed, though. doku has one shard with two copies – on qdrant-0 (vdb2) and qdrant-1 (vdb4). qdrant-2 has no copy and only forwards the requests that the Service assigns to it. vdb4 has two vCPUs and is already at 57 %.

Step 4 – load each copy individually. The Service distributes the requests across all three pods. If you ask a pod directly, you see what its copy can handle on its own. Insert the pod IP of qdrant-0:

# on vdb1
~/werkbank/bin/python last-prozesse.py http://10.42.1.34:6333 doku ../tag01/fragen.npy 16 8000

Expected:

parallel 16 (Prozesse) · 8000 Anfragen in 21.9 s · 365 Anfragen/s · p50 33.5 ms · p95 66.2 ms · p99 86.6 ms · max 150.9 ms · Fehler 0

And that of qdrant-1:

# on vdb1
~/werkbank/bin/python last-prozesse.py http://10.42.3.21:6333 doku ../tag01/fragen.npy 16 8000

Expected:

parallel 16 (Prozesse) · 8000 Anfragen in 33.0 s · 242 Anfragen/s · p50 60.9 ms · p95 105.7 ms · p99 130.3 ms · max 224.2 ms · Fehler 0

What you see: the same shard, the same data – on vdb4 with two vCPUs it manages two thirds of the throughput of vdb2, at double the median. Through the Service, both mix. Whoever measures the Service measures the average of fast and slow buildings; the slow ones determine the p99.

Remember: a load generator needs enough CPU itself – in Python that means processes instead of threads. And the performance of a collection is the performance of the nodes its copies live on.

Save your progress? Sign up for free

Drill 4: Books in crates – batch size

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: measured how much batch size speeds up ingestion.

Step 1 – create an empty collection.

# on vdb1
curl -s -X PUT http://10.43.151.237:6333/collections/einspielen -H 'Content-Type: application/json' -d '{"vectors":{"size":768,"distance":"Cosine"}}'
  • PUT /collections/einspielen creates the collection.
  • size 768 and distance Cosine match the vectors from Day 1.
  • You don’t specify shards and copies – Qdrant chooses itself.

Expected:

{"result":true,"status":"ok","time":2.307534761}

Step 2 – check what Qdrant chose.

# on vdb1
curl -s http://10.43.151.237:6333/collections/einspielen -o ein.json
# on vdb1
jq -c '.result.config.params' ein.json

Expected:

{"vectors":{"size":768,"distance":"Cosine"},"shard_number":6,"replication_factor":1,"write_consistency_factor":1,"on_disk_payload":true}

What you see: without a setting, Qdrant in a cluster creates two shards per peer – six with three peers – and no second copy. That is enough for a measurement; for production data you always specify both yourself (Day 5).

Step 3 – write the ingestion program. It writes the first ANZAHL vectors from Day 1 in batches of PAKET points. Each request waits until Qdrant has confirmed receipt (wait=True).

# on vdb1
nano einspielen.py
~/labor/tag08/einspielen.py new file
"""Schreibt die ersten ANZAHL Vektoren aus Tag 1 in Paketen der Größe PAKET und misst den Durchsatz."""
import sys
import time

import numpy as np
from qdrant_client import QdrantClient, models

QDRANT, COLLECTION, PAKET, ANZAHL = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])

vektoren = np.load("../tag01/vektoren.npy")[:ANZAHL]
client = QdrantClient(url=QDRANT, timeout=60)

start = time.perf_counter()
for anfang in range(0, ANZAHL, PAKET):
    paket = [models.PointStruct(id=i, vector=vektoren[i].tolist())
             for i in range(anfang, min(anfang + PAKET, ANZAHL))]
    client.upsert(COLLECTION, points=paket, wait=True)
dauer = time.perf_counter() - start
print(f"Paketgröße {PAKET}: {ANZAHL} Punkte in {dauer:.1f} s · {ANZAHL / dauer:.0f} Punkte/s"
      f" · {-(-ANZAHL // PAKET)} Anfragen")
Line Meaning
range(0, ANZAHL, PAKET) start numbers of the batches: 0, PAKET, 2 × PAKET …
min(anfang + PAKET, ANZAHL) the last batch is shorter if ANZAHL does not divide evenly
upsert(…, wait=True) write and wait for the confirmation
-(-ANZAHL // PAKET) number of requests, rounded up

Step 4 – write individually. One point per request – this is how a naive program writes that embeds each record and stores it immediately. So that it doesn’t take too long, only 2000 points.

# on vdb1
~/werkbank/bin/python einspielen.py http://10.43.151.237:6333 einspielen 1 2000

Expected:

Paketgröße 1: 2000 Punkte in 62.1 s · 32 Punkte/s · 2000 Anfragen

Step 5 – write in batches. Now all 13,220 points, in batches of 10:

# on vdb1
~/werkbank/bin/python einspielen.py http://10.43.151.237:6333 einspielen 10 13220

Expected:

Paketgröße 10: 13220 Punkte in 91.8 s · 144 Punkte/s · 1322 Anfragen

Repeat the command with 100 and 1000 instead of the 10.

Expected (all four runs):

Batch size Points Duration Points/s Requests
1 2,000 62.1 s 32 2,000
10 13,220 91.8 s 144 1,322
100 13,220 23.3 s 568 133
1000 13,220 14.3 s 923 14

What you see: between individually and batches of 1000 lies a factor of 29. Every request costs a fixed amount – HTTP, forwarding to the shard, an entry in the accession register (WAL) on a Longhorn volume that itself replicates over the network – no matter whether it contains one point or a thousand. With one point per request, that is about 31 ms per point. The vectors from Day 1 have 768 dimensions; a batch of 1000 is about 15 MB as JSON. Even larger batches hardly gain anything more and cost memory in the client and the server.

Remember: ingest in batches, not individually. A few hundred points per request is a good start – measured, not guessed.

Save your progress? Sign up for free

Drill 5: A million books with a ready-made catalog – glove-100

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: 1.18 million vectors in Qdrant, the time for ingestion and for indexing – and a ground truth you don’t have to compute yourself.

The 13,220 sections in doku are too few to put memory and index under pressure. For measurements there are public datasets with a ready-made ground truth. The ann-benchmarks project uses them to compare search methods; its dataset glove-100-angular contains 1,183,514 word vectors with 100 dimensions, 10,000 test questions and for each question the 100 exact nearest neighbors.

Step 1 – download the dataset. The file is 463 MB.

# on vdb1
curl -s -o glove-100-angular.hdf5 http://ann-benchmarks.com/glove-100-angular.hdf5
  • -s without a progress display.
  • -o glove-100-angular.hdf5 saves under this name.
# on vdb1
ls -lh glove-100-angular.hdf5

Expected (excerpt):

-rw-rw-r-- 1 ubuntu ubuntu 463M Dec  5 22:27 glove-100-angular.hdf5

Step 2 – install the HDF5 reader. HDF5 is a file format for large numeric arrays; h5py reads it in Python.

# on vdb1
~/werkbank/bin/pip install -q h5py
  • -q reports only errors.
# on vdb1
~/werkbank/bin/pip show h5py

Expected (excerpt – the line with Version):

Version: 3.16.0

Step 3 – split up the dataset. The program shows what is in the file and writes three numpy files: the holdings, the first 1000 test questions and, for each, the ten correct neighbors.

# on vdb1
nano glove-vorbereiten.py
~/labor/tag08/glove-vorbereiten.py new file
"""Liest glove-100-angular.hdf5 und legt Bestand, Fragen und Wahrheit als numpy-Dateien ab."""
import h5py
import numpy as np

with h5py.File("glove-100-angular.hdf5", "r") as datei:
    for name in datei:
        print(f"{name}: {datei[name].shape} {datei[name].dtype}")
    np.save("glove-bestand.npy", datei["train"][:])
    np.save("glove-fragen.npy", datei["test"][:1000])
    np.save("glove-wahrheit.npy", datei["neighbors"][:1000, :10])
print("gespeichert: glove-bestand.npy, glove-fragen.npy (1000), glove-wahrheit.npy (1000 x 10)")
Line Meaning
h5py.File(…, "r") open the file read-only
datei["train"] the holdings: the vectors that go into the database
datei["test"][:1000] the first 1000 test questions
datei["neighbors"][:1000, :10] for each of these questions, the IDs of the ten exact nearest holdings vectors
# on vdb1
~/werkbank/bin/python glove-vorbereiten.py

Expected:

distances: (10000, 100) float32
neighbors: (10000, 100) int32
test: (10000, 100) float32
train: (1183514, 100) float32
gespeichert: glove-bestand.npy, glove-fragen.npy (1000), glove-wahrheit.npy (1000 x 10)

What you see: 1,183,514 vectors times 100 dimensions times 4 bytes is 473 MB of pure vector data – 90 times as many vectors as in doku, but each only just under an eighth as long. The IDs in neighbors are the row numbers in the holdings. That is why each point in Qdrant gets its row number as its ID.

Step 4 – create the collection. This time you specify shards and copies yourself: three shards, one per pod, and no second copy. For a measurement collection that you can reload at any time, one copy is enough – for production data it is not.

# on vdb1
curl -s -X PUT http://10.43.151.237:6333/collections/glove -H 'Content-Type: application/json' -d '{"vectors":{"size":100,"distance":"Cosine"},"shard_number":3,"replication_factor":1}'
Setting Value Meaning
size 100 dimension of the glove vectors
distance Cosine “angular” in the dataset’s name means angle, that is, cosine
shard_number 3 three shelf sections, one per building
replication_factor 1 no second copy

Expected:

{"result":true,"status":"ok","time":1.741491859}

Step 5 – write the load program. Qdrant’s Python library comes with upload_collection: it splits the holdings into batches and sends them from several processes at the same time.

# on vdb1
nano glove-laden.py
~/labor/tag08/glove-laden.py new file
"""Lädt den glove-Bestand in Paketen von 1000 Punkten mit vier parallelen Prozessen."""
import sys
import time

import numpy as np
from qdrant_client import QdrantClient

QDRANT, COLLECTION = sys.argv[1], sys.argv[2]

if __name__ == "__main__":          # Pflicht, weil upload_collection Prozesse startet
    bestand = np.load("glove-bestand.npy")
    client = QdrantClient(url=QDRANT, timeout=120)
    start = time.perf_counter()
    client.upload_collection(COLLECTION, vectors=bestand, ids=range(len(bestand)),
                             batch_size=1000, parallel=4, wait=True)
    dauer = time.perf_counter() - start
    print(f"{len(bestand)} Punkte in {dauer:.0f} s · {len(bestand) / dauer:.0f} Punkte/s")
Line Meaning
ids=range(len(bestand)) point ID = row number, matching neighbors
batch_size=1000 1000 points per request – the result from Drill 4
parallel=4 four processes send at the same time
wait=True each request waits for the confirmation
if __name__ == "__main__": without this line the program aborts: each of the four processes reloads the file and would itself start four processes again

The last point is not a matter of style. In the first attempt the line was missing, and every worker process ended with RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase.

Step 6 – load.

# on vdb1
~/werkbank/bin/python glove-laden.py http://10.43.151.237:6333 glove

Expected:

1183514 Punkte in 197 s · 6009 Punkte/s

What you see: a little over 6000 points per second – six and a half times the 923 from Drill 4. The vectors are shorter (100 instead of 768 numbers) and four processes send at the same time.

Step 7 – watch the optimizer. Loaded is not finished. Query the state:

# on vdb1
curl -s http://10.43.151.237:6333/collections/glove -o g.json
# on vdb1
jq -c '.result|{status,optimizer_status,points_count,indexed_vectors_count,segments_count}' g.json

Expected (right after loading):

{"status":"yellow","optimizer_status":"ok","points_count":1183514,"indexed_vectors_count":635363,"segments_count":16}

Repeat the two commands until status shows green. For us this took a little over four minutes:

{"status":"green","optimizer_status":"ok","points_count":1183514,"indexed_vectors_count":1166917,"segments_count":8}

What you see:

Field Value Meaning
status yellow → green yellow: the optimizer is working; green: done
indexed_vectors_count 635,363 → 1,166,917 vectors already in the HNSW graph
segments_count 16 → 8 the optimizer merges book trolleys

1,166,917 is not quite all of them: 16,597 points are in no graph. This fits small segments below the indexing threshold from Day 4 – Qdrant searches such segments without an index. In total, about eight minutes passed from the start of loading to green – a little over three for loading, a little over four for the index.

Remember: ingested is not shelved. Only when the collection is green do you measure search – before that you are measuring the optimizer as well.

Save your progress? Sign up for free

Drill 6: Recall and response time with a ready-made ground truth

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: a table of recall versus hnsw_ef for a million vectors – and a lesson about measurement noise.

Step 1 – write the measurement program. Like recall.py from Day 4, but against the supplied ground truth. The fourth parameter only comes into play in Drill 7.

# on vdb1
nano glove-recall.py
~/labor/tag08/glove-recall.py new file
"""Misst recall@10 auf glove-100 gegen die mitgelieferte Wahrheit (1000 Fragen)."""
import sys

import numpy as np
from qdrant_client import QdrantClient, models

QDRANT, COLLECTION = sys.argv[1], sys.argv[2]
EF = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] != "-" else None
RESCORE = not (len(sys.argv) > 4 and sys.argv[4] == "ohne-rescore")

fragen = np.load("glove-fragen.npy")
wahrheit = np.load("glove-wahrheit.npy")
client = QdrantClient(url=QDRANT, timeout=60)
parameter = models.SearchParams(hnsw_ef=EF,
                                quantization=models.QuantizationSearchParams(rescore=RESCORE))

treffer = 0
for vektor, beste10 in zip(fragen, wahrheit):
    punkte = client.query_points(COLLECTION, query=vektor.tolist(), limit=10,
                                 search_params=parameter).points
    treffer += len({p.id for p in punkte} & set(beste10.tolist()))
print(f"ef {EF or 'Standard'} · rescore {'an' if RESCORE else 'aus'}"
      f" · recall@10 {treffer / (len(fragen) * 10):.3f}")
Line Meaning
sys.argv[3] hnsw_ef; - means default
sys.argv[4] == "ohne-rescore" optional: don’t re-check candidates against the original vectors (Drill 7)
QuantizationSearchParams(rescore=…) only takes effect if the collection is quantized
{p.id …} & set(beste10.tolist()) how many of the ten correct IDs came back
len(fragen) * 10 1000 questions × 10 = 10,000 possible hits

Ties as on Day 4 play no role with glove: duplicate word vectors are rare, so the program simply counts the intersection.

Step 2 – measure recall at hnsw_ef 10.

# on vdb1
~/werkbank/bin/python glove-recall.py http://10.43.151.237:6333 glove 10

Expected:

ef 10 · rescore an · recall@10 0.595

Repeat the command with 32, 64, 128, 256 and - instead of the 10.

Expected (all six runs, m 16, ef_construct 100):

hnsw_ef recall@10
10 0.595
32 0.777
64 0.846
Default 0.882
128 0.899
256 0.942

What you see: with the same index parameters as doku (0.992 on Day 4), glove reaches only 0.882 at the default. glove is a known hard dataset: word vectors lie densely and unevenly, and there are 90 times as many points. A setting that is enough for 13,000 points is not enough for a million. That is why you measure with your own data at your own size.

Step 3 – the response time with 16 readers. First a short run to warm up:

# on vdb1
~/werkbank/bin/python last-prozesse.py http://10.43.151.237:6333 glove glove-fragen.npy 16 2000

Expected:

parallel 16 (Prozesse) · 2000 Anfragen in 6.7 s · 297 Anfragen/s · p50 39.1 ms · p95 74.3 ms · p99 99.3 ms · max 129.7 ms · Fehler 0

Then with hnsw_ef 64 – that is the sixth parameter:

# on vdb1
~/werkbank/bin/python last-prozesse.py http://10.43.151.237:6333 glove glove-fragen.npy 16 8000 64

Expected:

parallel 16 (Prozesse) · 8000 Anfragen in 28.2 s · 283 Anfragen/s · p50 44.4 ms · p95 90.8 ms · p99 119.6 ms · max 199.8 ms · Fehler 0

Repeat with 128 and 256, then once more with 64 and 128.

Expected (all five runs in this order):

hnsw_ef Run Requests/s p50 p95 p99
64 1 283 44.4 ms 90.8 ms 119.6 ms
128 1 310 43.2 ms 81.5 ms 101.8 ms
256 1 238 54.6 ms 101.0 ms 132.5 ms
64 2 330 38.8 ms 77.2 ms 103.1 ms
128 2 287 45.9 ms 88.2 ms 115.8 ms

What you see: in the first round, hnsw_ef 64 was slower than 128 – in the second the other way round. Between two runs with the same value, throughput and p99 vary by more than 10 %. The difference between 64 and 128 is smaller than this noise. Only 256 is clearly slower: about a fifth less throughput than the average of the other runs. Every glove search queries all three shards – including those on the nodes with two vCPUs.

Remember: a single measurement is an anecdote. Repeat every level at least once; if the difference is smaller than the variation between repetitions, there is none.

Save your progress? Sign up for free

Drill 7: The paperback edition – scalar quantization

Where you are: on vdb1, in ~/labor/tag08.

What you have afterwards: measured what quantization costs and gains in recall, memory and time.

Each component of a vector is a 32-bit floating-point number, that is, 4 bytes. Scalar quantization maps it to an integer from 0 to 255, that is, 1 byte. A glove vector shrinks from 400 to 100 bytes. The search then runs on the small version; with rescore, the best candidates are re-evaluated with the original vectors at the end.

Step 1 – look at memory beforehand.

# on vdb1
kubectl -n qdrant top pods

Expected (the MEMORY column is what counts – the CPU is still from the last run):

NAME       CPU(cores)   MEMORY(bytes)   
qdrant-0   4317m        479Mi           
qdrant-1   1238m        383Mi           
qdrant-2   1358m        316Mi           

Step 2 – switch on quantization. This works on an existing collection.

# on vdb1
curl -s -X PATCH http://10.43.151.237:6333/collections/glove -H 'Content-Type: application/json' -d '{"quantization_config":{"scalar":{"type":"int8","quantile":0.99,"always_ram":true}}}'
Setting Value Meaning
PATCH /collections/glove change the settings of an existing collection
scalar scalar quantization, each component individually
type int8 one byte per component
quantile 0.99 the outermost 1 % of values are cut off so that outliers don’t stretch the scale
always_ram true the quantized version always stays in RAM

Expected:

{"result":true,"status":"ok","time":0.366220471}

Step 3 – wait until the optimizer is done. Qdrant builds the quantized version in the background.

# on vdb1
curl -s http://10.43.151.237:6333/collections/glove -o g.json
# on vdb1
jq -c '.result|{status,optimizer_status,indexed_vectors_count,segments_count,q:.config.quantization_config}' g.json

Expected (right afterwards):

{"status":"yellow","optimizer_status":"ok","indexed_vectors_count":1166917,"segments_count":8,"q":{"scalar":{"type":"int8","quantile":0.99,"always_ram":true}}}

Repeat both commands until status shows green – for us after a little over two minutes.

Step 4 – recall with quantization.

# on vdb1
~/werkbank/bin/python glove-recall.py http://10.43.151.237:6333 glove 128

Expected:

ef 128 · rescore an · recall@10 0.901

Step 5 – recall without looking it up in the hardcover edition.

# on vdb1
~/werkbank/bin/python glove-recall.py http://10.43.151.237:6333 glove 128 ohne-rescore

Expected:

ef 128 · rescore aus · recall@10 0.863

Step 6 – response time with quantization, twice.

# on vdb1
~/werkbank/bin/python last-prozesse.py http://10.43.151.237:6333 glove glove-fragen.npy 16 8000 128

Expected:

parallel 16 (Prozesse) · 8000 Anfragen in 24.0 s · 334 Anfragen/s · p50 40.4 ms · p95 75.3 ms · p99 97.6 ms · max 184.6 ms · Fehler 0

The same command once more:

parallel 16 (Prozesse) · 8000 Anfragen in 24.7 s · 324 Anfragen/s · p50 39.2 ms · p95 77.2 ms · p99 102.1 ms · max 166.1 ms · Fehler 0

Step 7 – look at memory afterwards.

# on vdb1
kubectl -n qdrant top pods

Expected:

NAME       CPU(cores)   MEMORY(bytes)   
qdrant-0   3964m        522Mi           
qdrant-1   1182m        425Mi           
qdrant-2   1316m        358Mi           

What you see – all at hnsw_ef 128, 16 readers:

without quantization int8, rescore on int8, rescore off
recall@10 0.899 0.901 0.863
Requests/s (2 runs) 310 / 287 334 / 324 –
p99 (2 runs) 101.8 / 115.8 ms 97.6 / 102.1 ms –
Memory qdrant-0 479 Mi 522 Mi –
  • Recall: with rescore no loss – 0.901 instead of 0.899 is within the margin. Without rescore, just under 4 percentage points are missing: the paperback edition alone confuses close neighbors.
  • Time: a little more throughput, just above the noise. The original vectors were already in RAM, and a large part of every response time is spent on the HTTP round trip anyway.
  • Memory: more, not less. qdrant-0 holds about 424,000 points; 100 additional bytes per point is about 40 MB – matching the 43 Mi more. After all, the originals are kept.

Quantization only shows its benefit when the original vectors move to disk and only the small version stays in RAM (on_disk plus always_ram). Then four times as many vectors fit into the same memory. That is the topic of Day 9.

Remember: quantization with rescore costs hardly any recall, without rescore noticeably more. As long as the originals stay in RAM, it costs memory instead of saving it – it only saves memory together with on_disk.

Save your progress? Sign up for free

Diagnosis task: The median lies

A colleague reports: “Search has been sluggish for a quarter of an hour.” The dashboard shows the median response time – and it is unchanged. You run the load generator from Drill 3 with 16 readers:

parallel 16 (Prozesse) · 8000 Anfragen in 41.7 s · 192 Anfragen/s · p50 31.6 ms · p95 114.0 ms · p99 320.0 ms · max 2522.3 ms · Fehler 0

Compare with Drill 3. What is going on, and where do you look?

Find the cause before you read on.

Solution, step by step.

  1. The numbers side by side:
Value Drill 3 (16 readers) now Factor
Requests/s 455 192 0.4
p50 29.0 ms 31.6 ms 1.1
p95 53.7 ms 114.0 ms 2.1
p99 69.5 ms 320.0 ms 4.6
max 110.4 ms 2522.3 ms 23

The median has hardly moved, the edge has multiplied, throughput has halved. Most requests are as fast as usual, a few wait a very long time – the picture of contention for CPU or disk, not of a slower index.

  1. Look at the pods and nodes:
# on vdb1
kubectl top nodes
NAME   CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)   
vdb1   2267m        18%      2843Mi          22%         
vdb2   1627m        20%      1434Mi          8%          
vdb3   1169m        58%      937Mi           11%         
vdb4   1804m        90%      1137Mi          14%         

vdb4 with its two vCPUs is at 90 %. One of the two copies of doku lives there.

  1. Look at the collections: curl -s http://10.43.151.237:6333/collections/glove -o g.json, then jq -c '.result|{status,optimizer_status,points_count,indexed_vectors_count,segments_count}' g.json:
{"status":"yellow","optimizer_status":"ok","points_count":259080,"indexed_vectors_count":0,"segments_count":11}

Another collection is currently being ingested – exactly the load from Drill 5, recorded after about a minute. The same three pods are simultaneously writing the accession register and segments for glove and answering the searches on doku.

The fix: run large ingestion jobs outside peak hours or throttle them (fewer parallel processes, smaller batches), don’t concentrate read and write load on the same weak node, and don’t use weak nodes as data nodes. For comparison: later, when glove had already been ingested and only the index was being built, the same run yielded 438 requests/s with p99 87.2 ms – in this lab, building the index was far less disruptive than the ingestion itself.

Remember: an unchanged median proves nothing. If p99 and maximum rise and throughput falls, look for someone who currently needs the same nodes for something else.

Cleanup and checkpoint

You no longer need the collection einspielen from Drill 4.

# on vdb1
curl -s -X DELETE http://10.43.151.237:6333/collections/einspielen

Expected:

{"result":true,"status":"ok","time":0.347425349}

glove stays – on Day 9 you use it to calculate how much memory a vector needs.

Checkpoint:

# on vdb1
curl -s http://10.43.151.237:6333/collections

Expected:

{"result":{"collections":[{"name":"doku"},{"name":"glove"},{"name":"verteilt"}]},"status":"ok","time":0.000064418}
# on vdb1
kubectl -n qdrant exec qdrant-1 -- df -h /qdrant/storage
  • exec qdrant-1 -- runs the following command in the pod.
  • df -h /qdrant/storage shows the usage of the Longhorn volume in readable units.

Expected (the first line only reports which container is meant):

Defaulted container "qdrant" out of: qdrant, ensure-dir-ownership (init)
Filesystem                                              Size  Used Avail Use% Mounted on
/dev/longhorn/pvc-e760fa38-f3f3-446d-9edc-6453b63e6b61  3.9G  390M  3.5G  10% /qdrant/storage
# on vdb1
kubectl -n longhorn-system get volumes.longhorn.io -o custom-columns=NAME:.metadata.name,ROBUST:.status.robustness

Expected: all volumes healthy.

# on vdb1
kubectl -n qdrant get pods

Expected: three pods 1/1 Running, RESTARTS 0 – even after a million points and some tens of thousands of searches, no pod has reached its memory limit of 2 Gi.

Test yourself

  1. Your load generator reports the same throughput for 4, 16 and 64 readers. What do you check before judging Qdrant?
  2. Why is p99 a more important figure for a search application than the median?
  3. Why is one point per write request so much slower than a thousand?
  4. A collection has just finished loading. Why don’t you measure search yet?
  5. Two runs with hnsw_ef 64 and 128 yield 283 and 310 requests per second. Is 128 faster?
  6. You switch on scalar quantization, and memory usage rises. A bug or expected?

Answers:

  1. The load generator itself: top on the client. In Drill 2 the Python process was at 100 % of one core while Qdrant together did not even need one core. With processes instead of threads, throughput with 16 readers rose from 133 to 455.
  2. Because a page with ten searches or a RAG answer with several queries almost always catches a slow value, and because the median hides disruptions – in the diagnosis task it stayed at 32 ms while p99 rose to 320 ms.
  3. Every request costs a fixed amount: HTTP, forwarding to the shard, an entry in the WAL on a replicated Longhorn volume. Measured: 32 points/s individually, 923 points/s in batches of 1000.
  4. Because the optimizer is still merging segments and building the index (status yellow). That costs CPU and distorts the measurement; glove still needed a little over four minutes after loading.
  5. Not proven. The repetition yielded 330 and 287 – the other way round. The difference is within the noise.
  6. Expected, as long as the original vectors stay in RAM: the quantized version is added on top, for glove about 100 bytes per point. Quantization only saves memory together with on_disk for the originals.

Interview note

“How do you measure the performance of a vector database?” – With a closed load generator that has enough CPU – in Python with processes, not threads – and only once the collection is green, after a warm-up run. I state throughput together with parallelism and p50, p95, p99, and always with dataset, dimension, index parameters and hardware. I measure recall against a ground truth: for comparisons with a public dataset like glove-100, for decisions with my own data at my own size. I repeat every level to know the noise. When ingesting, batch size and parallelism count; during large loads, search p99 rises if both run on the same nodes.

Enterprise note

In production, load tests run as a repeatable job with a fixed dataset and a fixed question catalog; the results end up in a table with version, index parameters and node type – that way a regression after an upgrade (Day 15) becomes visible. For open load (requests arrive independently of the answers) there are tools like k6 or vegeta; a closed generator like today’s underestimates waiting time under overload. Large ingestion jobs get their own time window or a throttle, and an SLO for search is formulated on p99, not on the average (Day 11). Data nodes get uniform hardware – a weak node with a copy determines the p99 of all requests that land on it.

Summary

  • The first run of a test was cold: p99 142 ms instead of 21 ms with the same median.
  • With Python threads, it topped out at about 140 requests/s – limited by the load generator (100 % of one core), not by Qdrant. With processes: 455 requests/s with 16 readers (p99 70 ms), 564 with 32 (p99 122 ms) on doku (13,220 vectors, 768 dimensions, m 16, ef_construct 100).
  • The same shard managed 365 requests/s on vdb2 (8 vCPU) and 242 on vdb4 (2 vCPU).
  • Ingestion: 32 points/s individually, 144 with batches of 10, 568 with 100, 923 with 1000.
  • glove-100 (1,183,514 vectors, 100 dimensions, three shards without a second copy): loaded in 197 s (6009 points/s), green a little over four minutes later. recall@10 0.595 at hnsw_ef 10, 0.882 at the default, 0.942 at 256.
  • Variation between repetitions: over 10 %. Only hnsw_ef 256 was clearly slower.
  • Scalar quantization int8 with rescore: recall 0.901 (without rescore 0.863), throughput slightly higher, memory about 40 MB more per pod.
  • During a large load, search throughput halved, p99 rose from 70 to 320 ms, and the median stayed at about 30 ms.

Commands at a glance

Command Purpose
~/werkbank/bin/python last.py <url> <collection> <fragen.npy> <parallel> <count> [ef] load generator with threads
~/werkbank/bin/python last-prozesse.py <url> <collection> <fragen.npy> <parallel> <count> [ef] load generator with processes
kubectl -n qdrant top pods CPU and memory of the Qdrant pods
top -b -n1 CPU of the processes on the client
~/werkbank/bin/python einspielen.py <url> <collection> <batch> <count> measure ingestion with a fixed batch size
curl -s -o glove-100-angular.hdf5 http://ann-benchmarks.com/glove-100-angular.hdf5 download a benchmark dataset with ground truth
~/werkbank/bin/python glove-vorbereiten.py holdings, questions, ground truth as numpy files
~/werkbank/bin/python glove-laden.py <url> glove ingest a million vectors in parallel
jq -c '.result\|{status,optimizer_status,points_count,indexed_vectors_count,segments_count}' g.json progress of the optimizer
~/werkbank/bin/python glove-recall.py <url> glove <ef\|-> [ohne-rescore] recall@10 against the glove ground truth
curl -s -X PATCH <url>/collections/glove -H 'Content-Type: application/json' -d '{"quantization_config":{"scalar":{"type":"int8","quantile":0.99,"always_ram":true}}}' switch on scalar quantization
kubectl -n qdrant exec qdrant-1 -- df -h /qdrant/storage usage of the Qdrant volume

Contents

More