Tune AgentDB storage and search with the shipped primitives: 8-bit/4-bit scalar and product quantization stores, the vector backend choice (ruvector or hnswlib), QueryCache, BatchOperations, and the agentdb stats/doctor CLI. Use when an AgentDB store uses too much memory, search is slow, or you need to measure before tuning.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Agentdb Optimization?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ruvnet-agentdb-optimization-c64ffcb7)
---
name: agentdb-optimization
description: "Tune AgentDB storage and search with the shipped primitives: 8-bit/4-bit scalar and product quantization stores, the vector backend choice (ruvector or hnswlib), QueryCache, BatchOperations, and the agentdb stats/doctor CLI. Use when an AgentDB store uses too much memory, search is slow, or you need to measure before tuning."
---
# AgentDB Performance Optimization
## What This Skill Does
Covers the optimization building blocks the `agentdb` package exports, and how to measure
before and after changing them:
- **Quantization** - `createScalar8BitStore`, `createScalar4BitStore`, `createProductQuantizedStore`
(`QuantizedVectorStore`), plus `quantize8bit` / `quantize4bit` / `getQuantizationStats`.
- **Vector backend** - `new AgentDB({ vectorBackend: 'auto' | 'ruvector' | 'hnswlib' })`.
- **Caching** - `QueryCache` (LRU with hit-rate statistics).
- **Batching** - `BatchOperations` for bulk episode / skill / pattern inserts.
- **Measurement** - `agentdb stats`, `agentdb db stats`, `agentdb doctor`, `agentdb status`.
No speed-up figure in this skill is a promise: the gain depends on vector count, dimension and
backend. Measure on your own data. There is no `createAgentDBAdapter` factory and no
`agentdb benchmark` command; use the classes and verbs below.
## Prerequisites
- Node.js 20+
- `agentdb` 3.10+ (`npm install agentdb`; it is also a dependency of `@claude-flow/cli`)
---
## Quick Start: Measure First
```bash
# Backend detection and system health
npx agentdb@latest doctor --verbose
npx agentdb@latest init ./agentdb.db --dry-run
# Database statistics
npx agentdb@latest stats ./agentdb.db
npx agentdb@latest status --db ./agentdb.db --verbose
```
`init --dry-run` shows which vector backend would be used without creating anything.
---
## Choosing the Vector Backend
```typescript
import { AgentDB, isHnswlibAvailable } from 'agentdb';
console.log('hnswlib available:', await isHnswlibAvailable());
const db = new AgentDB({
dbPath: '.agentdb/vectors.db',
vectorBackend: 'auto', // 'auto' (default) | 'ruvector' | 'hnswlib'
vectorDimension: 384,
});
await db.initialize();
console.log('backend:', db.vectorBackendName, 'sql.js fallback:', db.isWasm);
await db.close();
```
From the CLI: `npx agentdb@latest init ./agentdb.db --backend ruvector --dimension 384`.
`isWasm` is `true` when native `better-sqlite3` could not load and AgentDB fell back to sql.js;
`npm rebuild better-sqlite3` restores the native driver.
---
## Quantization
`QuantizedVectorStore` keeps compressed vectors in memory and searches them directly.
```typescript
import {
createScalar8BitStore,
createScalar4BitStore,
createProductQuantizedStore,
getQuantizationStats,
} from 'agentdb';
const dim = 384;
const vectors: Float32Array[] = loadEmbeddings(); // your data
// Scalar 8-bit: about 4x smaller than float32
const sq8 = createScalar8BitStore(dim, 'cosine'); // metric: 'cosine' | 'l2' | 'ip'
vectors.forEach((v, i) => sq8.insert(`doc-${i}`, v));
const hits = sq8.search(vectors[0], 10); // [{ id, similarity, ... }]
console.log(sq8.getStats()); // includes compressionRatio, memoryUsageBytes
// Scalar 4-bit: smaller again, with more reconstruction error
const sq4 = createScalar4BitStore(dim, 'cosine');
// Product quantization: must be trained before insert/search
const pq = createProductQuantizedStore(dim, 8, 256, 'cosine'); // numSubspaces, numCentroids
await pq.train(vectors);
console.log(pq.isReady());
// Error / compression for one vector before committing to a scheme
console.log(getQuantizationStats(vectors[0], '8bit')); // { meanError, maxError, compressionRatio, ... }
```
Check recall against an unquantized search on a sample of your own queries before switching.
### 1-bit (RaBitQ) quantization
`agentdb` does not export a binary quantizer. For 1-bit compression of ruflo's memory store use the
ruflo MCP tools `mcp__claude-flow__embeddings_rabitq_build`,
`mcp__claude-flow__embeddings_rabitq_search` and `mcp__claude-flow__embeddings_rabitq_status`
(see the `vector-quantization` skill).
---
## Caching
```typescript
import { QueryCache } from 'agentdb';
const cache = new QueryCache({ maxSize: 1000 });
const key = cache.generateKey('SELECT * FROM episodes WHERE task = ?', ['login'], 'episodes');
// ... run the query on a miss, store the result, read it back on a hit
console.log(cache.getStatistics()); // { hits, misses, hitRate, size, capacity, evictions, ... }
cache.invalidateCategory('episodes'); // after writes to that table
```
`ReflexionMemory` and `SkillLibrary` already accept a `QueryCacheConfig`, and `SkillLibrary`
exposes `getCacheStats()` / `warmCache(tasks)`.
---
## Batch Operations
Insert many rows in one transaction instead of one call per row.
```typescript
import { AgentDB, EmbeddingService, BatchOperations } from 'agentdb';
const db = new AgentDB({ dbPath: '.agentdb/vectors.db' });
await db.initialize();
const embedder = new EmbeddingService({
model: 'Xenova/all-MiniLM-L6-v2', dimension: 384, provider: 'transformers',
});
await embedder.initialize();
const batch = new BatchOperations(db.database, embedder);
const inserted = await batch.insertEpisodes([
{ sessionId: 's1', task: 'fix login bug', reward: 0.9, success: true },
{ sessionId: 's1', task: 'add rate limit', reward: 0.7, success: true },
]);
console.log('inserted', inserted);
// Compact the database after a large load
batch.optimize();
await db.close();
```
Other bulk methods: `insertSkills`, `insertPatterns`, `batchInsertParallel`, `bulkUpdate`,
`bulkDelete`, `regenerateEmbeddings`. To remove stale rows use the CLI `prune` verbs below
(`BatchOperations#pruneData` fails in agentdb 3.10.0 with `no such column: ts`).
---
## Memory Cleanup from the CLI
```bash
# Consolidate patterns and compress
npx agentdb@latest optimize-memory --compress true --consolidate-patterns true
# Prune low-value episodes, skills and causal edges
npx agentdb@latest reflexion prune 90 0.3
npx agentdb@latest skill prune 3 0.4 60
npx agentdb@latest learner prune 0.5 0.05 90
# Reclaim SQLite space
sqlite3 ./agentdb.db "VACUUM;"
```
---
## Troubleshooting
### High memory use
Move cold vectors into a `createScalar8BitStore` / `createProductQuantizedStore` store, or prune
with the commands above. Check `getStats().memoryUsageBytes` before and after.
### Slow search
Check `db.vectorBackendName`; if it is not the backend you expected, see `agentdb doctor`. Keep
`k` as small as the task allows.
### Low recall after quantizing
Use 8-bit instead of 4-bit, or more PQ subspaces/centroids, and re-measure recall.
---
## Learn More
- `npx agentdb@latest --help` - the full CLI reference for the installed version
- Type definitions: `node_modules/agentdb/dist/src/quantization/vector-quantization.d.ts`,
`core/QueryCache.d.ts`, `optimizations/BatchOperations.d.ts`
- Source: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
---
**Category**: Performance / Optimization
**Difficulty**: Intermediate