Vladyslav Krylasov's website

Scaling LanceDB: Running 700 million vectors in production

Published on

Library Database by Jan Antonin Kolar
Contents

Note. The context manager approach, which opens and closes the connection and table on each use like ConnectionManager below, works for lancedb==0.21.2.

Update on 09.09.2025. lancedb==0.25.0 fixed the issues with connect_async, and the old context manager pattern now causes memory leaks. Use a singleton for connections and tables instead. See the example at the end.

Also read the warning under the hourly optimize script in the Versioning section before you copy any of the scripts.

Introduction

This article covers how I moved a vector database from Milvus to LanceDB. Milvus cost too much to run, so I looked for something cheaper. LanceDB looked like it could cut costs and still be fast enough for this much data.

I moved 700 million vectors and got LanceDB running in production, but hit a few problems along the way. The sections below go through each one and how I fixed it.

Problems

Indexing

Copying the 700 million vectors from Milvus to LanceDB went fine. Indexing them did not.

I needed two indexes, a scalar BTree index and a vector IvfPq index.

The BTree index built without trouble in several hours.

>>> from lancedb import connect_async
>>> from lancedb.index import BTree

>>> conn = await connect_async(uri="/storage/lancedb")
>>> table = await conn.open_table("documents")

>>> await  table.create_index(
    column="id",
    config=BTree(),
    replace=False
)

>>> await table.list_indices()
[Index(BTree, columns=["id"], name="id_idx")]

>>> await table.index_stats("id_idx")
IndexStatistics(
    num_indexed_rows=700_000_000,
    num_unindexed_rows=0,
    index_type='BTREE',
    distance_type=None,
    num_indices=1,
)

The IvfPq index was harder. While building it, LanceDB writes temporary data to /tmp, and that volume didn’t have room for the gigabytes it needed. LanceDB’s data already lived on a separate volume, so I pointed TMPDIR there.

$ export TMPDIR=/storage/lancedb
>>> from lancedb import connect_async
>>> from lancedb.index import IvfPq

>>> conn = await connect_async(uri="/storage/lancedb")
>>> table = await conn.open_table("documents")

>>> await table.create_index(
    column="vector",
    config=IvfPq(
        distance_type="l2",
        num_partitions=26_457,
        num_sub_vectors=64
    ),
    replace=False
)

The docs give these formulas for num_partitions and num_sub_vectors:

  • $ \text{number of partitions} = \sqrt{\text{number of rows}} $
  • $ \text{number of subvectors} = \frac{\text{vector dimension}}{16} $

The vector index build ran for about a day, then failed because it ran out of RAM, even though the machine had 128GB. I dug into it for a while, then gave up and tried something else. Instead of indexing the whole dataset at once, I split it into chunks of 50 million documents. The vector index for the first 50 million built without problems.

>>> from lancedb import connect_async
>>> from lancedb.index import IvfPq

>>> conn = await connect_async(uri="/storage/lancedb")
>>> table = await conn.open_table("documents")

>>> await table.create_index(
    column="vector",
    config=IvfPq(
        distance_type="l2",
        num_partitions=7071,
        num_sub_vectors=64
    ),
    replace=False
)

>>> await table.list_indices()
[
    Index(BTree, columns=["id"], name="id_idx"),
    Index(
        IvfPq, columns=["vector"], name="vector_idx"
    )
]
>>> await table.index_stats("vector_idx")
IndexStatistics(
    num_indexed_rows=50_000_000,
    num_unindexed_rows=0,
    index_type='IVF_PQ',
    distance_type='l2',
    num_indices=1,
)

After each 50 million chunk, I ran optimize. LanceDB builds an index once and doesn’t add new data to it on its own, so you have to call optimize every time you add data.

>>> from datetime import timedelta
>>> from lancedb import connect_async

>>> conn = await connect_async(uri="/storage/lancedb")
>>> table = await conn.open_table("documents")

>>> await table.optimize(
    cleanup_older_than=timedelta(seconds=0),
    delete_unverified=True
)

Batching plus optimize got both the scalar and vector indexes built for the whole dataset.

Memory leaks

Once LanceDB went into production, memory leaks showed up fast. It ran behind an API under Uvicorn, and search worked fine, but memory use kept growing.

Connections and tables should close after each operation, but they piled up and ate memory. To fix that, I added a connection manager that closes both on exit.

To try it yourself, set up LanceDB with a dataset and watch memory usage. Below are the requirements.txt and a script that uses the connection manager.

# Ran on Python 3.11.11
# requirements.txt 
annotated-types==0.7.0
deprecation==2.1.0
lancedb==0.21.2
loguru==0.7.3
numpy==2.2.4
overrides==7.7.0
packaging==24.2
pandas==2.2.3
pyarrow==19.0.1
pydantic==2.11.1
pydantic-core==2.33.0
python-dateutil==2.9.0.post0
pytz==2025.2
six==1.17.0
tqdm==4.67.1
typing-extensions==4.13.0
typing-inspection==0.4.0
tzdata==2025.2
# This script creates a lance table with
# 10k documents/vectors via connection manager.
import asyncio

import numpy as np
from lancedb.db import AsyncConnection, AsyncTable
from lancedb.pydantic import LanceModel, Vector
from loguru import logger
from pydantic import Field

from lancedb import connect_async


def generate_normalised_vectors(
    *,
    num_vectors: int,
    dimension: int = 512,
    max_distance: float = 1.0,
):
    # Generate random vectors
    vectors = np.random.randn(num_vectors, dimension)

    # Normalize vectors to unit length (L2 norm = 1)
    norms = np.linalg.norm(vectors, axis=1)
    norm_vecs = vectors / norms[:, np.newaxis]

    # Scale each vector by a random factor between 0
    # and max_distance
    scales = (
        np.random.rand(num_vectors) * max_distance
    )
    scaled_vectors = norm_vecs * scales[:, np.newaxis]

    return scaled_vectors


class ConnectionManager:
    table: AsyncTable

    def __init__(
        self,
        *,
        conn: AsyncConnection,
        table_name: str
    ) -> None:
        self.conn = conn
        self.table_name = table_name

    async def __aenter__(self):
        self.table = await self.conn.open_table(
            self.table_name
        )
        logger.debug(
            f"Opened LanceDB table {self.table_name}"
        )

        return self

    async def __aexit__(self, exc_type, exc, tb):
        self.table.close()
        self.conn.close()
        logger.debug(
            "Closed LanceDB table "
            f"{self.table_name} & its connection."
        )


class Document(LanceModel):
    id: int
    title: str
    content: str
    distance: float = Field(
        alias="_distance", default=0.0
    )
    vector: Vector(512)


async def main():
    # Establish a connection with a LanceDB.
    conn = await connect_async(uri="/storage/lancedb")

    # Create a lance table based on pydantic
    # `Document` schema.
    await conn.create_table(
        name="documents",
        schema=Document,
        mode="create",
    )

    # Open documents table and close its connection &
    # table upon exit from an async context manager.
    async with ConnectionManager(
        conn=conn,
        table_name="documents"
    ) as manager:
        # Generate 10k pydantic `Document` instances
        # with normalised vectors.
        vectors = generate_normalised_vectors(
            num_vectors=10_000
        )
        documents = [
            Document(
                id=i,
                title=f"Document {i}",
                content=f"Content of document {i}",
                vector=vectors[i],
            )
            for i in range(10_000)
        ]
        await manager.table.add(documents)

        # Get first 100 documents from documents table
        # and validate them with a pydantic model.
        raw_documents = (
            await manager.table.query()
            .limit(100)
            .to_list()
        )
        documents = [
            Document.model_validate(doc)
            for doc in raw_documents
        ]

        # Iterate through 100 documents and find 5 most
        # similar vectors based on the base vector
        # from a document.
        for doc in documents:
            raw_docs = await (
                manager.table.vector_search(
                    query_vector=doc.vector
                )
                # don't include itself in a search
                .where(f"id != {doc.id}")
                .limit(5)
                .to_list()
            )
            docs = [
                Document.model_validate(doc)
                for doc in raw_docs
            ]

            # Show only vectors with a close distance.
            for doc in docs:
                if doc.distance > 0.8:
                    logger.info(
                        f"Doc id: {doc.id}, "
                        f"distance {doc.distance}."
                    )


asyncio.run(main())

Disk storage

Versioning

Alongside the indexing and memory problems, disk usage grew into terabytes.

Most of it came from LanceDB’s versioning, which keeps old versions of the data. Each operation on the table writes new files to directories like these:

  • /storage/lancedb/documents.lance/_transactions
  • /storage/lancedb/documents.lance/_versions

To keep this in check, I ran optimize every hour. It adds new data to the indexes and deletes all previous versions of the table. It doesn’t lock the table, so vector search keeps working while it runs.

# hourly script
from datetime import timedelta
from lancedb import connect_async

conn = await connect_async(uri="/storage/lancedb")
table = await conn.open_table("documents")

await table.optimize(
    # such params delete previous versions
    cleanup_older_than=timedelta(seconds=0),
    delete_unverified=True
)

Warning. Don’t use cleanup_older_than=timedelta(seconds=0) with delete_unverified=True while anything else writes to the table, even from a different script. The cleanup step then deletes files from writes that haven’t finished yet. It can work for weeks, then optimize fails with an error like this:

LanceError(IO): External error: Not found: /storage/lancedb/documents.lance/data/<file>.lance

A LanceDB maintainer called this combination very dangerous, and the LanceDB docs say to set delete_unverified=True only if no other process is working on the dataset, or it can end up corrupted. More details are in issue #2963.

I keep adding data while optimize runs. These settings work for me:

await table.optimize(
    cleanup_older_than=timedelta(minutes=15),
    delete_unverified=False,
)

Indexes

Search keeps working during optimize because optimize leaves the old indexes alone. It builds new indexes from the existing ones plus the unindexed data, then switches to them. After that you can delete the old indexes to free disk space.

$ ls -lt /storage/lancedb/documents.lance/_indices
drwxrwxr-x 2 vald vald 4096 бер 30 17:06 aa9325d8-8cd2-4373-870b-94e26c1ad732
drwxrwxr-x 2 vald vald 4096 бер 30 17:06 9b93c185-52dd-4e54-8cae-c4ba1b0d9f66
# NOTE: below directories can be deleted assuming
# you have only two indexes scalar and vector ones
drwxrwxr-x 2 vald vald 4096 бер 30 17:01 5484f99e-dda2-4caa-bce4-8ea7987fff61
drwxrwxr-x 2 vald vald 4096 бер 30 17:00 125fee6d-6170-4600-b084-3680a7b35e59

Every optimize run leaves new index directories behind, so I automated the cleanup. A cron job runs a script that keeps only the two newest directories, one for the scalar index and one for the vector index, and deletes the older ones. This assumes the table has just those two indexes.

import asyncio
import argparse
import shutil
from datetime import timedelta
from pathlib import Path

from lancedb import connect_async
from loguru import logger


async def main(
    lancedb_path: str,
    table_names: list[str]
) -> None:
    lancedb_volume = Path(lancedb_path)

    lock_file = lancedb_volume / ".lock-file"
    if lock_file.exists():
        logger.warning("LanceDB optimisation, cleanup process is in progress. Exiting...")
        return

    lock_file.touch()
    db = await connect_async(uri=lancedb_path)

    logger.debug(
        f"LanceDB volume path: {lancedb_path}"
    )
    logger.debug(
        "Going to process "
        f"the following tables: {table_names}"
    )
    print()

    for table_name in table_names:
        table = await db.open_table(table_name)

        # Clean up files in dirs _versions,
        # _transactions, merge data in data dir, add
        # new vectors into scalar and vector indexes.
        logger.warning(
            f"Optimizing {table_name} table..."
        )
        await table.optimize(
            cleanup_older_than=timedelta(minutes=15),
            delete_unverified=False,
        )
        logger.info(
            f"Finished optimizing {table_name} table."
        )

    print()

    # Remove .tmp* directories in LanceDB data volume
    # after `optimize` runs.
    for item in lancedb_volume.rglob(".tmp*"):
        if item.is_dir():
            logger.warning(
                "Deleting temporary "
                f"directory: {item}"
            )
            shutil.rmtree(item)

    print()

    # Delete indexes duplicates in each directory of
    # table and leave only the latest scalar and
    # vector ones.
    for table_name in table_names:
        table_dir = Path(
            f"{lancedb_path}/{table_name}"
            ".lance/_indices"
        )
        index_dirs = sorted(
            (
                item
                for item in table_dir.iterdir()
                if item.is_dir()
            ),
            key=lambda d: d.stat().st_mtime,
            reverse=True,
        )
        for index_dir in index_dirs[2:]:
            logger.warning(
                "Deleting index "
                f"directory: {index_dir}"
            )
            shutil.rmtree(index_dir)

    lock_file.unlink()



if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--lancedb-path",
        type=str,
        default="/storage/lancedb",
        help="Path where LanceDB data lives",
    )
    parser.add_argument(
        "--table-names",
        type=str,
        default="documents",
        help="Comma separated list of tables",
    )
    args = parser.parse_args()
    table_names = args.table_names.split(",")

    asyncio.run(
        main(
            lancedb_path=args.lancedb_path,
            table_names=table_names,
        )
    )

Final thoughts

In the end, after fixing all issues, 700 million documents took 1.6TB of disk instead of $ \infty \text{TB} $, on a machine with 16 CPUs and 128GB of RAM.

Moving from Milvus to LanceDB cut our monthly costs from 30,000 USD to 7,000 USD. It needs more manual upkeep, but it was worth it.

Update (09.09.2025)

LanceDB singleton connector

With newer LanceDB versions, use a singleton so the app creates the connection once and reuses it. Opening and closing connections over and over is what leaks memory in the new versions.

Tables are different. Call open_table() on every request. A table you keep open still points to the old indexes while optimize() builds new ones and deletes the old ones, so the next query fails with LanceError(IO) saying the index does not exist.

from typing import Self

from lancedb import (
    AsyncConnection,
    AsyncTable,
    connect_async
)


class LanceDBConnector:
    """Singleton class for LanceDB connection
    & tables management"""

    instance: Self | None = None
    conn: AsyncConnection | None = None
    tables: dict[str, AsyncTable] = {}

    def __new__(cls) -> "LanceDBConnector":
        if cls.instance is None:
            cls.instance = super().__new__(cls)

        return cls.instance

    async def get_connection(self) -> AsyncConnection:
        if self.conn is None:
            self.conn = await connect_async(
                uri="/storage/lancedb"
            )

        return self.conn

    async def close(self) -> None:
        for table in self.tables.values():
            table.close()

        self.tables.clear()

        if self.conn:
            self.conn.close()
            self.conn = None

Cleanup script

LanceDB fixed the stale indexes, so the cron script changes too. It now deletes only empty index directories instead of everything but the two newest, and uses the safer optimize settings from the warning above.

import asyncio
import argparse
import shutil
from datetime import timedelta
from pathlib import Path

from lancedb import connect_async
from loguru import logger


async def main(
    lancedb_path: str, table_names: list[str]
) -> None:
    lancedb_volume = Path(lancedb_path)

    lock_file = lancedb_volume / ".lock-file"
    if lock_file.exists():
        logger.warning(
            "LanceDB optimisation, cleanup process is in progress. Exiting..."
        )
        return

    lock_file.touch()
    db = await connect_async(uri=lancedb_path)

    logger.debug(
        f"LanceDB volume path: {lancedb_path}"
    )
    logger.debug(
        f"Going to process the following tables: {table_names}"
    )
    print()

    for table_name in table_names:
        table = await db.open_table(table_name)

        # Clean up files in dirs _versions, _transactions, merge data in data
        # dir, add new vectors into scalar and vector indices.
        logger.warning(
            f"Optimizing {table_name} table..."
        )
        await table.optimize(
            cleanup_older_than=timedelta(minutes=15),
            delete_unverified=False,
        )
        logger.info(
            f"Finished optimizing {table_name} table."
        )

    print()

    # Remove .tmp* directories in LanceDB data after `optimize` runs.
    for item in lancedb_volume.rglob(".tmp*"):
        if item.is_dir():
            logger.warning(
                f"Deleting temporary directory: {item}"
            )
            shutil.rmtree(item)

    print()

    # Delete empty index directories inside each table
    for table_name in table_names:
        table_dir = Path(
            f"{lancedb_path}/{table_name}.lance/_indices"
        )
        if not table_dir.exists():
            continue

        for index_dir in table_dir.iterdir():
            if index_dir.is_dir() and not any(
                index_dir.iterdir()
            ):
                logger.warning(
                    f"Deleting empty index directory: {index_dir}"
                )
                shutil.rmtree(index_dir)

    lock_file.unlink()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--lancedb-path",
        type=str,
        default="/storage/lancedb",
        help="Path where LanceDB data lives",
    )
    parser.add_argument(
        "--table-names",
        type=str,
        default="documents",
        help="Comma separated list of tables",
    )
    args = parser.parse_args()
    table_names = args.table_names.split(",")

    asyncio.run(
        main(
            lancedb_path=args.lancedb_path,
            table_names=table_names,
        )
    )