TitanDB Documentation
TitanDB is a high-performance, embedded and cloud-ready NoSQL database engine written in 100% safe Rust. Engineered for local-first developer ergonomics, microsecond point-in-time recovery, and zero-compromise speed on any server hardware.
New to Databases? (Explain Like I'm 5)
If you are a beginner, think of databases as electronic filing cabinets:
- What is a Document Database? In traditional databases (SQL), data must fit into strict, rigid rows and columns. In TitanDB, data is saved as JSON Documents — exactly like the JavaScript objects you use every day in your frontend or backend code!
- What is Write-Ahead Logging (WAL)? Imagine a shopkeeper who writes every transaction into a diary before putting money in the drawer. If the power cuts, he simply looks at the diary to see what happened. That's WAL — it guarantees zero data loss even during system crashes!
- What is Multi-Tenancy? Imagine an apartment building where everyone has their own private key and room. In TitanDB, every developer or user automatically gets their own isolated sandbox partition (
tenant_<key_id>) without their data mixing!
Why Choose TitanDB?
| Feature | TitanDB | MongoDB | SQLite | DynamoDB |
|---|---|---|---|---|
| Binary Size | 1.78 MB (Single Static Executable) | > 500 MB (Heavy daemon) | ~ 2 MB (Embedded C library) | Cloud Only (Proprietary) |
| Setup Overhead | Zero Setup (1 click run) | Complex (Service configs) | Zero Setup | AWS Account required |
| Point-in-Time Recovery (PITR) | Built-in (Microsecond) | Enterprise / Atlas Only | Manual Backups | Supported ($$) |
| Embedded Studio Web UI | Built-in at /studio (Offline) | Separate 300MB Compass App | No Web UI | AWS Web Console |
| Language / Memory Safety | 100% Safe Rust | C++ | C | Java |
0.246 ms average TCP latency with immediate TCP_NODELAY and single-syscall response buffering.
Every API key is automatically bound to an isolated tenant partition with zero cross-tenant contamination.
Microsecond WAL timestamps allow continuous archiving and millisecond-precision rollback to any past point.
256-bit CSPRNG keys, constant-time verification, path traversal barriers, and Slowloris protections.
Zero runtime dependencies. No heavy JVM, no complex C++ libraries. Just drop the binary and run.
Full Node.js & TypeScript SDK with Schema validation, pre/post middleware, and auto-provisioning.
Databases were supposed to store and retrieve data safely at the speed of light. Instead, our industry settled for 600MB Docker containers, unpredictable garbage collector stutters, cloud vendor lock-in tax, and fear of touching production migrations. TitanDB was engineered to tear that status quo down.
The Bloat Dilemma: Why Modern Databases Frustrate Developers
Let’s be brutally honest about the state of databases in 2026:
- The RAM & Container Tax: Why does spinning up a basic NoSQL database for a microservice require 1.5GB of RAM, 4 YAML config files, and 10 minutes of Docker image pulling? Why can't a database just be a 1.78 MB static binary that starts in 4 milliseconds?
- The Cloud Hostage Situation: Modern cloud database giants charge you for every single read unit, connection drop, and gigabyte egress. If you leave a dev database running overnight on AWS or MongoDB Atlas, you wake up to an invoice. Your database should be sovereign software that you own 100%.
- The SQLite vs MongoDB False Choice: Developers love SQLite because it's a single file and runs anywhere. But SQLite is strictly relational, lacks built-in HTTP APIs, has no native secondary index ergonomics for JSON, and no multi-tenant isolation. On the flip side, MongoDB has great document ergonomics, but it's massive, written in C++, requires separate 300MB GUI apps (Compass), and runs heavy background daemons.
The 5 Core Architectural Axioms
0.006 ms reads). Over HTTP TCP sockets, it immediately disables Nagle's 40ms buffering algorithm (TCP_NODELAY) and merges headers and body into a single network packet. The result: 0.246 ms average roundtrip latency under sustained multi-threaded concurrency.
tenant_<key_id>). Two customers writing order_1 will never collide or leak data. Anti-spoofing headers reject unauthorized tenant access with an instant 403 Forbidden.
AI / LLM Integration Knowledge Base (1-Click)
Building with ChatGPT, Claude, Cursor, Windsurf, Copilot, Gemini, v0, or Bolt? Copy the complete TitanDB LLM Knowledge Base in one click and paste it into any AI assistant — it will generate 100% accurate, zero-hallucination TitanDB integration code for your exact stack.
Instant AI Integration Pack (SDK + REST + ACID + Express/Next.js)
Includes exact npm package rules (titandb-sdk), production HTTPS endpoint, 3-line CRUD API, Mongoose-style ODM, multi-document ACID transaction schema, REST API paths, and drop-in Express / Next.js / Python recipes.
https://titandb.arpankhan.online/llms.txt to @Docs or paste into .cursorrules for permanent AI context.
Preview Exact AI Knowledge Base Prompt (llms.txt)
Loading TitanDB LLM Knowledge Base...
Quickstart in 60 Seconds
Get up and running with TitanDB in less than a minute:
Step 1: Start the TitanDB Server
Run the standalone binary in your terminal:
# Start TitanDB on port 8080 (Local Dev Mode)
titandb serve --port 8080
# Or start with Cloud Security & RBAC enabled
titandb serve --port 8080 --cloud
Ultra-Fast 3-Line Integration (Zero Boilerplate)
Zero schemas, zero migrations, zero manual table provisioning. Tables auto-create on first write. Connect and read/write in literally 3 lines of code:
// 1. Connect • 2. Put • 3. Get — 3 Lines. Done.
const db = require('titandb-sdk')('https://titan.api.arpankhan.online', 'titan_sec_live_your_key');
await db.table('users').set('usr_1', { name: 'Arpan', role: 'developer' });
const user = await db.table('users').get('usr_1'); // <0.3ms latency
Step 2: Connect in Code (Choose your language & style)
TitanDB provides native client SDKs and a universal REST API for all languages:
// 1. Install SDK in terminal:
// npm install titandb-sdk
//
// 2. app.js — Unified Cloud & Local Integration (Zero Schemas, Auto-Provisioning):
const { TitanDB } = require('titandb-sdk');
// Cloud Production (with API Key in URI):
const db = new TitanDB('titandb://titan_sec_live_your_key@titan.api.arpankhan.online/analytics');
// Or Local Offline: const db = new TitanDB('titandb://127.0.0.1:8080/analytics');
async function main() {
// Write document (database & table auto-provision on first write, like MongoDB):
await db.users.insert({ id: 'usr_1', name: 'Arpan Khan', role: 'admin', active: true });
// Point-in-time read (<0.3ms latency)
const user = await db.users.get('usr_1');
console.log('Retrieved User:', user);
// Direct property proxy query:
const allUsers = await db.users.all();
console.log('All Users:', allUsers);
}
main().catch(console.error);
// 1. Install SDK in terminal:
// npm install titandb-sdk
//
// 2. Create index.js and paste this code:
const titandb = require('titandb-sdk');
const { Schema } = titandb;
async function run() {
// Connect to TitanDB Cloud (or 'http://localhost:8080' for local dev)
await titandb.connect({
url: 'https://titandb.arpankhan.online',
apiKey: 'titan_sec_live_your_project_key', // Sent via X-API-Key
});
console.log('Connected to TitanDB Cloud successfully!');
// Define Schema with auto-indexing
const UserSchema = new Schema({
name: { type: String, required: true },
role: { type: String, enum: ['admin', 'dev'], default: 'dev', index: true },
score: { type: Number, default: 0 },
});
const User = titandb.model('users', UserSchema);
// Insert and Query
await User.create({ id: 'u1', name: 'Arpan', role: 'admin', score: 100 });
// Read back
const admins = await User.find({ role: 'admin' });
console.log('Found Admins:', admins);
}
run();
// 3. Run in terminal: node index.js
# 1. Install in terminal:
# pip install requests
#
# 2. Create app.py and paste this code:
import requests
# Production Cloud URL & X-API-Key
BASE_URL = "https://titan.api.arpankhan.online/v1"
HEADERS = {
"X-API-Key": "titan_sec_live_your_project_key",
"Content-Type": "application/json",
}
# Insert a document (PUT)
doc = {"name": "Arpan", "role": "admin", "score": 100}
requests.put(f"{BASE_URL}/tables/users/documents/u1", json=doc, headers=HEADERS)
print("Document saved to Cloud!")
# Fast point lookup by ID (GET)
user = requests.get(f"{BASE_URL}/tables/users/documents/u1", headers=HEADERS).json()
print("Found user:", user)
# Filtered Query (POST)
res = requests.post(
f"{BASE_URL}/tables/users/query",
json={"condition": "role == 'admin'"},
headers=HEADERS,
).json()
print("All admins:", res)
# 3. Run in terminal: python app.py
# 1. Set Production Endpoint & Secret Key
export TITANDB_URL="https://titan.api.arpankhan.online/v1"
export TITANDB_KEY="titan_sec_live_your_project_key"
# 2. Save document via PUT with X-API-Key
curl -X PUT "$TITANDB_URL/tables/users/documents/u1" \
-H "X-API-Key: $TITANDB_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "Arpan", "role": "admin", "score": 100}'
# 3. Get document by ID
curl -H "X-API-Key: $TITANDB_KEY" "$TITANDB_URL/tables/users/documents/u1"
# 4. Query table with condition
curl -X POST "$TITANDB_URL/tables/users/query" \
-H "X-API-Key: $TITANDB_KEY" \
-H "Content-Type: application/json" \
-d '{"condition": "role == '\''admin'\''"}'
use titandb::{Database, wal::WalWriter, transaction::ConcurrentEngine};
use serde_json::json;
use std::path::Path;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut db = Database::new();
db.create_table("users")?;
let wal = WalWriter::open(Path::new("titan.wal"))?;
let engine = ConcurrentEngine::new(db, wal);
// In-process nanosecond write
engine.put_doc("users", "u1", json!({"name": "Arpan", "role": "admin"}), None)?;
let doc = engine.get_doc("users", "u1")?;
println!("Retrieved from RAM: {:?}", doc);
Ok(())
}
Installation & CLI Reference
TitanDB is distributed as a single static binary with zero external runtime dependencies.
Cloud & Official SDK Installation
# 1. Install the official TitanDB Client SDK in your project
npm init -y && npm install titandb-sdk
# 2. Create a database project & copy your X-API-Key from:
# https://titandb.arpankhan.online
Server Modes: Local Dev vs Cloud RBAC
TitanDB supports two primary execution modes depending on your environment:
- Local Dev Mode (Default):
titandb serve --port 8080. Open authentication, ideal for local testing, frontend prototyping, and offline mobile/desktop apps. - Cloud RBAC Mode:
titandb serve --port 8080 --cloud. Generates a secure 256-bit SHA-256 root admin key on startup. Enforces strict authentication (X-API-Key), role permissions (Admin, ReadWrite, ReadOnly), and automatic per-key multi-tenant sandboxes.
Beginner Troubleshooting FAQ
titandb serve --port 9090.
titan.db (the persistent snapshot) and titan.wal (the live transaction journal). You can set a custom storage directory with --data-dir /my/data.
Architecture & Engine Internals
TitanDB combines an in-memory concurrent SkipList table with persistent Log-Structured Merge-Tree (LSM-Tree) SSTables, Bloom Filters, and microsecond Write-Ahead Logging (WAL).
Adaptive Worker Pool (Speed on Any Hardware)
Unlike naive database servers that spawn an OS thread for every incoming HTTP socket (which crashes low-spec VPS servers due to context-switch thrashing and thread-stack allocation), TitanDB utilizes a Pre-Warmed Hardware-Adaptive Worker Pool:
- Low-End VPS (1 vCPU / 512MB RAM): Caps pool threads at 4, locking memory usage to under 15MB.
- Enterprise Cloud (32 to 64 Cores): Scales up to 64 pre-warmed workers, processing tens of thousands of concurrent requests with zero thread allocation overhead.
- TCP_NODELAY: Nagle's algorithm is disabled immediately upon socket accept, eliminating the 40ms to 200ms kernel buffering latency.
- Single-Syscall Response Buffering: HTTP headers and JSON bodies ≤ 64 KB are merged into a single network packet, cutting syscall overhead by 10x.
Node.js & TypeScript ODM SDK
The official titandb-sdk npm package provides a production-grade Object Data Modeling (ODM) layer inspired by Mongoose, with complete TypeScript definitions.
Installation
# Inside your project folder (run npm init -y first if starting a brand-new folder)
npm init -y && npm install titandb-sdk
SDK Versions & Zero Breaking Changes Guarantee
v0.2.4 LatestTitanDB follows strict semantic backward-compatibility. Code written for older versions (v0.2.0 – v0.2.3) will NEVER break when updating to v0.2.4+. Choose the syntax that fits your project version below:
| Feature | v0.2.4+ (Latest) | v0.2.0 – v0.2.3 (Legacy LTS) |
|---|---|---|
| Connection String URI | ✅ titandb://host:8080/my_db |
Options object (url + tenantId) |
| Dynamic Table Proxy | ✅ db.users.insert(...) |
Explicit helper db.table('users').insert(...) |
| Factory Syntax | ✅ Backward-compatible (100% supported) | ✅ Native require('titandb-sdk')(...) |
| Explicit Table Helper | ✅ Backward-compatible (100% supported) | ✅ Native db.table('name') |
| Dynamic Auto-DB Provisioning | ✅ Automatic on first write | ✅ Automatic on first write via tenantId |
// titandb-sdk@^0.2.4 — Modern Connection URI & Dynamic Table Proxy
const { TitanDB } = require('titandb-sdk');
async function main() {
// 1. Connect using titandb:// URI (target database auto-partitions):
const db = new TitanDB('titandb://127.0.0.1:8080/analytics');
// 2. Dynamic property proxy auto-creates table and inserts record:
const res = await db.users.insert({
id: 'usr_101',
name: 'Arpan',
role: 'founder'
});
console.log('Inserted:', res);
// Point-in-time fetch:
const user = await db.users.get('usr_101');
console.log('User:', user);
}
main().catch(console.error);
// titandb-sdk@0.2.0 – 0.2.3 — Factory Function & Explicit Table Helper
const titandb = require('titandb-sdk');
async function main() {
// 1. Connect using factory function and explicit options:
const db = titandb({
url: 'http://127.0.0.1:8080',
tenantId: 'analytics'
});
// 2. Explicit table helper auto-creates table and inserts record:
const res = await db.table('users').insert({
id: 'usr_101',
name: 'Arpan',
role: 'founder'
});
console.log('Inserted:', res);
// Point-in-time fetch:
const user = await db.table('users').get('usr_101');
console.log('User:', user);
}
main().catch(console.error);
3-Line Quick Integration (Zero Boilerplate)
Don't need Mongoose schemas or complex models? Want dead-simple serverless storage in literally 3 lines? Initialize TitanDB with a single function call — tables are created automatically on first write:
// 1. Connect
const db = require('titandb-sdk')('https://titan.api.arpankhan.online', 'titan_sec_live_your_key');
// 2. Save document (tables auto-provision)
await db.table('users').set('usr_1', { name: 'Arpan', role: 'developer' });
// 3. Point lookup (<0.3ms latency)
const user = await db.table('users').get('usr_1');
// Even cleaner: Access any table as a direct property!
const db = require('titandb-sdk')('https://titan.api.arpankhan.online', 'titan_sec_live_your_key');
await db.users.set('usr_1', { name: 'Arpan' });
const user = await db.users.get('usr_1');
const allUsers = await db.users.all();
// Zero-config: Automatically reads TITANDB_URL & TITANDB_API_KEY from process.env
const db = require('titandb-sdk')();
await db.users.set('usr_1', { name: 'Arpan' });
const user = await db.users.get('usr_1');
| Method | Example | Description |
|---|---|---|
get(id) |
await db.table('users').get('u1') |
Sub-millisecond point lookup by document ID. |
set(id, doc) |
await db.table('users').set('u1', { name: 'Arpan' }) |
Persists document. Table is automatically created if absent. |
insert(doc) |
await db.table('orders').insert({ total: 99 }) |
Inserts document and auto-generates a unique ID if not provided. |
update(id, updates) |
await db.table('users').update('u1', { role: 'admin' }) |
Atomic partial document update. |
delete(id) |
await db.table('users').delete('u1') |
Deletes document by ID. |
all() |
await db.table('users').all() |
Returns all documents in the table as an Array. |
find(filter) |
await db.table('users').find({ role: 'admin' }) |
Finds documents matching key-value properties or condition expressions. |
What's Next? (Complete Copy-Paste Starter Code)
Right after running npm install titandb-sdk, create a new file named quickstart.js (or index.ts for TypeScript) and paste the complete boilerplate below. It shows how to connect, define schemas, insert data, and query in under 60 seconds:
npm install titandb-sdk
quickstart.js & paste code below
node quickstart.js
// quickstart.js — Literally 3 lines of code! Zero schemas, zero migrations.
const db = require('titandb-sdk')('https://titan.api.arpankhan.online', 'titan_sec_live_your_api_key');
async function main() {
// Line 2: Save document (tables auto-provision on first write)
await db.table('users').set('usr_1', { name: 'Arpan', role: 'developer', stars: 100 });
// Line 3: Read document (<0.3ms latency)
const user = await db.table('users').get('usr_1');
console.log('Done in 3 lines:', user);
// Bonus: Property Proxy shorthand works too!
const adminUser = await db.users.findOne({ role: 'developer' });
console.log('Found via index filter:', adminUser);
}
main();
// quickstart.js — Complete, runnable starter script
const titandb = require('titandb-sdk');
const { Schema, model } = titandb;
async function main() {
// 1. Connect to TitanDB cluster (Local dev or Cloud)
await titandb.connect({
url: 'http://localhost:8080', // Or your Cloud URL: https://titan.api.arpankhan.online
apiKey: 'titan_live_your_api_key', // Optional for local dev, required for Cloud mode
});
console.log('Connected to TitanDB cluster successfully!');
// 2. Define Schema with auto-indexing
const User = model('users', new Schema({
name: { type: String, required: true },
email: { type: String, required: true, index: true },
role: { type: String, default: 'developer', index: true },
points: { type: Number, default: 0 },
}));
// 3. Insert a Document (Instant write flushed to WAL)
const newUser = await User.create({
id: 'usr_101',
name: 'Arpan',
email: 'arpan@example.com',
role: 'architect',
points: 100,
});
console.log('Document created in <0.3ms:', newUser);
// 4. Point Lookup by Primary Key (O(1) in-memory cache hit)
const user = await User.findById('usr_101');
console.log('Retrieved user:', user.name, `(${user.email})`);
// 5. Query Secondary Index (O(log N) B-Tree scan)
const architects = await User.find({ role: 'architect' });
console.log(`Found ${architects.length} architect(s)`);
// 6. Atomic In-Place Update ($set and $inc operators)
await User.update('usr_101', {
$inc: { points: 50 },
$set: { status: 'promoted' },
});
console.log('Atomic update applied! New score: 150');
}
main().catch(console.error);
// quickstart.ts — Production TypeScript with strict interfaces
import titandb, { Schema, model } from 'titandb-sdk';
// 1. Define typed document interface
interface IUser {
id?: string;
name: string;
email: string;
role: 'developer' | 'architect' | 'admin';
points: number;
}
async function bootstrap() {
// 2. Connect client
await titandb.connect({
url: process.env.TITANDB_URL || 'http://localhost:8080',
apiKey: process.env.TITANDB_KEY,
});
// 3. Model with generic type safety
const User = model<IUser>('users', new Schema({
name: { type: String, required: true },
email: { type: String, required: true, index: true },
role: { type: String, enum: ['developer', 'architect', 'admin'], default: 'developer' },
points: { type: Number, default: 0 },
}));
// 4. Typesafe operations
const doc = await User.create({
name: 'Arpan',
email: 'arpan@example.com',
role: 'architect',
points: 100,
});
console.log('Inserted typed user:', doc.id);
}
bootstrap().catch(console.error);
// server.js — Instant REST API with Express + TitanDB
const express = require('express');
const titandb = require('titandb-sdk');
const app = express();
app.use(express.json());
// Connect to TitanDB before handling API traffic
titandb.connect({ url: 'http://localhost:8080' });
const Product = titandb.model('products', new titandb.Schema({
title: { type: String, required: true },
price: { type: Number, required: true },
inStock: { type: Boolean, default: true }
}));
// GET /products/:id — Sub-millisecond Point Lookup
app.get('/products/:id', async (req, res) => {
const item = await Product.findById(req.params.id);
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json(item);
});
// POST /products — Fast WAL Insert
app.post('/products', async (req, res) => {
const item = await Product.create(req.body);
res.status(201).json(item);
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Run your script:
node quickstart.js
Connected to TitanDB cluster successfully!
Document created in <0.3ms: { id: 'usr_101', name: 'Arpan', email: 'arpan@example.com', role: 'architect', points: 100 }
Retrieved user: Arpan (arpan@example.com)
Found 1 architect(s)
Atomic update applied! New score: 150
Defining Schemas with Validation & Secondary Indexes
Declare your data structure with automatic type checking, custom error messages, and auto-indexed attributes:
const { Schema, model } = require('titandb-sdk');
const OrderSchema = new Schema({
customer_id: { type: String, required: true, index: true },
status: { type: String, enum: ['pending', 'shipped', 'delivered'], default: 'pending' },
total_amount: { type: Number, min: 0, required: [true, 'Order total cannot be negative'] },
items: { type: Array, default: () => [] },
}, { timestamps: true });
// Declaring 'index: true' automatically builds secondary index 'idx_orders_customer_id'
const Order = model('orders', OrderSchema);
CRUD & Atomic Update Operators
// 1. Insert Document
const newOrder = await Order.create({
id: 'ord_9001',
customer_id: 'cust_42',
total_amount: 1250,
items: [{ sku: 'PROD_A', qty: 2 }]
});
// 2. Point Lookup by Primary Key
const order = await Order.findById('ord_9001');
// 3. Query via Global Secondary Index
const customerOrders = await Order.find({ customer_id: 'cust_42' });
// 4. Atomic Counter Update ($inc / $set)
await Order.update('ord_9001', {
$inc: { total_amount: 50 },
$set: { status: 'shipped' }
});
Fluent QueryBuilder
Chain intuitive filters, ranges, limits, and order clauses:
const topOrders = await Order.query()
.where('total_amount').gte(500)
.limit(25)
.exec();
Multi-Document ACID Transactions
Execute atomic, all-or-nothing mutations across multiple tables with canonical deadlock-free lock ordering:
await titandb.transactWrite([
{
type: 'UPDATE',
table: 'accounts',
key: 'acc_sender',
update: 'ADD balance -500',
condition: 'balance >= 500', // Fails atomically if balance insufficient
},
{
type: 'UPDATE',
table: 'accounts',
key: 'acc_receiver',
update: 'ADD balance 500',
}
]);
Automatic Multi-Tenant Isolation
// Scopes this model strictly to tenant 'org_acme'
const AcmeOrder = Order.withTenant('org_acme');
await AcmeOrder.create({ id: 'ord_1', total_amount: 100 });
// Scopes to another tenant without conflict
const GlobexOrder = Order.withTenant('org_globex');
await GlobexOrder.create({ id: 'ord_1', total_amount: 250 }); // Zero collision!
Connecting to TitanDB Cloud (Production & X-API-Key Guide)
TitanDB Cloud runs multi-tenant serverless clusters with automatic cryptographic partitioning, TLS 1.3 encryption, and sub-millisecond response guarantees.
Whether you connect via the official Node.js SDK, raw fetch(), Python, or cURL, all requests are authenticated via the X-API-Key header.
titandb://<your_api_key>@titan.api.arpankhan.online/<database>
https://titan.api.arpankhan.online
X-API-Key: titan_sec_live_<your_key> (or Bearer token)How Authentication & Multi-Tenancy Work
Every API key in TitanDB is a 256-bit cryptographically random token generated from OS CSPRNG entropy. When you supply your key:
- Zero Cross-Tenant Contamination: The engine hashes your key with HMAC-SHA256 in constant time, immediately binding your connection to your dedicated tenant sandbox (
tenant_<project_id>). - No Table Collisions: Two different developers can both have a table named
usersand a document namedusr_101. Their data will never collide, overwrite, or be visible to one another. - Anti-Spoofing Headers: If a client attempts to inject an unauthorized
X-Titan-Tenantheader, the gateway rejects the request with an instant 403 Forbidden.
Production Code Examples (Connect to Cloud)
Choose your stack below to see complete, tested snippets connecting to https://titan.api.arpankhan.online with X-API-Key:
// 1. Install official SDK: npm install titandb-sdk
const titandb = require('titandb-sdk');
const { Schema, model } = titandb;
async function connectProduction() {
// 2. Connect to TitanDB Cloud Production Endpoint with X-API-Key
await titandb.connect({
url: 'https://titan.api.arpankhan.online', // Direct Production API Endpoint
apiKey: process.env.TITANDB_API_KEY || 'titan_sec_live_9a8b7c6d5e4f3a2b1c0d', // Your Project Live Secret Key
});
console.log('Connected to TitanDB Cloud cluster over TLS 1.3!');
// 3. Define Schema & Model (Identical API to local development!)
const Customer = model('customers', new Schema({
name: { type: String, required: true },
email: { type: String, required: true, index: true },
plan: { type: String, enum: ['free', 'pro', 'enterprise'], default: 'pro' },
}));
// 4. Sub-millisecond Cloud Document Insert (Flushed to NVMe WAL)
const customer = await Customer.create({
id: 'cust_prod_901',
name: 'Arpan Khan',
email: 'arpan@arpankhan.online',
plan: 'enterprise',
});
console.log('Customer created in Cloud:', customer);
// 5. Point Lookup via Primary Key (O(1) L1 MemTable cache read)
const doc = await Customer.findById('cust_prod_901');
console.log('Fetched in <0.4ms from Cloud:', doc.name);
}
connectProduction().catch(console.error);
// Zero-dependency HTTP client for Next.js App Router, Cloudflare Workers, or Browser
const CLOUD_URL = 'https://titan.api.arpankhan.online/v1';
const API_KEY = process.env.TITANDB_API_KEY; // 'titan_sec_live_...'
// 1. Insert or Upsert Document (PUT)
async function saveDocument() {
const res = await fetch(`${CLOUD_URL}/tables/orders/documents/ord_771`, {
method: 'PUT',
headers: {
'X-API-Key': API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
customerId: 'cust_88',
amount: 4500,
currency: 'INR',
status: 'paid',
}),
});
return await res.json();
}
// 2. Point Lookup by Primary Key (GET)
async function getDocument(orderId) {
const res = await fetch(`${CLOUD_URL}/tables/orders/documents/${orderId}`, {
headers: { 'X-API-Key': API_KEY },
});
return await res.json();
}
// 3. Query Secondary Index (POST)
async function queryPaidOrders() {
const res = await fetch(`${CLOUD_URL}/tables/orders/query`, {
method: 'POST',
headers: {
'X-API-Key': API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
condition: "status == 'paid' && amount >= 1000",
}),
});
return await res.json();
}
import os
import requests
# Production Configuration
CLOUD_URL = "https://titan.api.arpankhan.online/v1"
API_KEY = os.getenv("TITANDB_API_KEY", "titan_sec_live_9a8b7c6d5e4f3a2b1c0d")
HEADERS = {
"X-API-Key": API_KEY,
"Content-Type": "application/json",
}
# 1. Put document into cloud partition
payload = {
"user_id": "usr_py_42",
"username": "arpandev",
"role": "admin",
"score": 98.5,
}
res = requests.put(f"{CLOUD_URL}/tables/users/documents/usr_py_42", json=payload, headers=HEADERS)
print("PUT Status:", res.status_code, "Payload:", res.json())
# 2. Point lookup by ID
user = requests.get(f"{CLOUD_URL}/tables/users/documents/usr_py_42", headers=HEADERS).json()
print("Found User in Cloud in <0.4ms:", user)
# 3. Secondary Index Query with Condition
query_res = requests.post(
f"{CLOUD_URL}/tables/users/query",
json={"condition": "role == 'admin' && score >= 90"},
headers=HEADERS,
).json()
print("Query Matches:", query_res)
# 1. Export production URL and Secret API Key
export TITANDB_URL="https://titan.api.arpankhan.online/v1"
export TITANDB_KEY="titan_sec_live_9a8b7c6d5e4f3a2b1c0d"
# 2. Insert Document with X-API-Key
curl -i -X PUT "$TITANDB_URL/tables/customers/documents/cust_101" \
-H "X-API-Key: $TITANDB_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "Arpan Khan", "email": "arpan@arpankhan.online", "tier": "gold"}'
# 3. Fast Point Lookup by Primary Key
curl -i -X GET "$TITANDB_URL/tables/customers/documents/cust_101" \
-H "X-API-Key: $TITANDB_KEY"
# 4. Filtered Query using Secondary Index
curl -i -X POST "$TITANDB_URL/tables/customers/query" \
-H "X-API-Key: $TITANDB_KEY" \
-H "Content-Type: application/json" \
-d '{"condition": "tier == '\''gold'\''"}'
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
const (
cloudURL = "https://titan.api.arpankhan.online/v1"
apiKey = "titan_sec_live_9a8b7c6d5e4f3a2b1c0d"
)
func main() {
client := &http.Client{Timeout: 5 * time.Second}
// Point lookup over HTTPS with X-API-Key
req, _ := http.NewRequest("GET", cloudURL+"/tables/customers/documents/cust_101", nil)
req.Header.Set("X-API-Key", apiKey)
start := time.Now()
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("Cloud Response: %d in %v\n", resp.StatusCode, time.Since(start))
}
Production Security & Environment Variables
Always keep your live production keys secret. In your application repository, store them in .env.production or your deployment dashboard (Vercel / AWS / Docker):
TITANDB_URL=https://titan.api.arpankhan.online
TITANDB_API_KEY=titan_sec_live_9a8b7c6d5e4f3a2b1c0d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b
titan_sec_live_...) is generated once and ready to use immediately!
Python & REST Integration
Python developers can connect directly via requests, httpx, or our lightweight wrapper class:
# 3 Lines. Done. Instant REST query against TitanDB Cloud
import requests
requests.put("https://titan.api.arpankhan.online/v1/tables/users/documents/u1", json={"name": "Arpan", "role": "dev"}, headers={"X-API-Key": "titan_sec_live_your_key"})
user = requests.get("https://titan.api.arpankhan.online/v1/tables/users/documents/u1", headers={"X-API-Key": "titan_sec_live_your_key"}).json()["document"]
print("Fetched in 3 lines:", user)
import requests
BASE_URL = "http://localhost:8080/v1"
HEADERS = {"X-API-Key": "titan_live_..."} # If cloud mode enabled
# 1. Put Document
doc = {"name": "Laptop", "price": 85000, "in_stock": True}
requests.put(f"{BASE_URL}/tables/products/documents/prod_1", json=doc, headers=HEADERS)
# 2. Get Document
res = requests.get(f"{BASE_URL}/tables/products/documents/prod_1", headers=HEADERS)
print("Retrieved:", res.json())
import requests
class TitanClient:
def __init__(self, base_url="http://localhost:8080", api_key=None):
self.base_url = f"{base_url}/v1"
self.headers = {"X-API-Key": api_key} if api_key else {}
def put(self, table, key, document):
return requests.put(f"{self.base_url}/tables/{table}/documents/{key}", json=document, headers=self.headers).json()
def get(self, table, key):
return requests.get(f"{self.base_url}/tables/{table}/documents/{key}", headers=self.headers).json()
def query(self, table, condition):
return requests.post(f"{self.base_url}/tables/{table}/query", json={"condition": condition}, headers=self.headers).json()
# Usage:
db = TitanClient()
db.put("items", "item_1", {"title": "Mouse", "price": 1200})
print(db.get("items", "item_1"))
Titan Streams (Change Data Capture - CDC)
Titan Streams emits strictly ordered, real-time mutation events (INSERT, MODIFY, REMOVE)
over Server-Sent Events (SSE). Use it to build live reactive dashboards, notifications, and cache invalidation pipes.
const eventSource = new EventSource('http://localhost:8080/v1/streams');
eventSource.onmessage = (event) => {
const change = JSON.parse(event.data);
console.log(`[${change.op_type}] Table: ${change.table}, Key: ${change.key}`);
console.log('Before:', change.old_image);
console.log('After:', change.new_image);
};
# Listen to live server events in terminal
curl -N -H "Accept: text/event-stream" http://localhost:8080/v1/streams
Interactive Query Playground (Try It Live)
Test sample queries below to see how TitanDB processes requests and returns sub-millisecond JSON envelopes:
// Click "Run Query" above to execute and inspect the JSON response envelope!
Security, RBAC & Multi-Tenancy
TitanDB is hardened with military-grade defenses against arbitrary execution, DoS bombs, and cross-tenant data leaks:
getrandom OS CSPRNG with 256 bits of true entropy (titan_live_<64-hex>), rendering brute-force mathematically impossible ($2^{256}$ keyspace).
- Constant-Time Verification: All API key checks execute in constant time (
constant_time_eq), eliminating side-channel timing attacks. - Path Traversal Defense: Directory traversal sequences (
..) and null-byte escapes (\0) are rejected across all backup, restore, and WAL archive routes. - Parser Recursion Bomb Limit: AST depth is capped at 64 levels (with 64KB max expression size), stopping stack-overflow crash attacks.
- Slowloris Defenses: Request lines capped at 8KB, headers at 100 max, and total headers at 64KB.
- Automatic Per-Auth Tenant Sandboxing: Non-admin users are automatically confined to
tenant_<key_id>. Any client injecting a mismatchedX-Titan-Tenantheader receives an immediate 403 Forbidden.
Point-In-Time Recovery (PITR)
TitanDB logs microsecond timestamps on every Write-Ahead Log (WAL) transaction. If a bad migration or accidental deletion occurs, you can roll back the database to any past millisecond without data loss.
# 1. Periodically archive WAL logs to cold storage
titandb archive-wal --wal titan.wal --archive-dir /backup/wal_archive
# 2. Roll back state to an exact historical timestamp (e.g. 5 minutes ago)
titandb pitr --target-time 1794049807782 --wal titan.wal --db titan.db
REST API Specification
Comprehensive reference of all standard REST API endpoints available on TitanDB:
| Method | Endpoint Path | Access | Description |
|---|---|---|---|
| GET | /v1/health |
Public | Health check and server engine uptime status. |
| GET | /v1/ready |
Public | Kubernetes & Cloud readiness probe (active connections, cache). |
| GET | /v1/metrics |
Public | Live Prometheus/JSON telemetry metrics. |
| GET | /v1/tables |
ReadOnly | List all tables in current tenant sandbox. |
| POST | /v1/tables |
Admin | Create a new table. |
| DELETE | /v1/tables/:name |
Admin | Drop table and its associated secondary indexes. |
| GET | /v1/tables/:name/documents/:key |
ReadOnly | Fetch document by primary key (0.2 ms point lookup). |
| PUT | /v1/tables/:name/documents/:key |
ReadWrite | Insert or replace document with optional IF condition. |
| PATCH | /v1/tables/:name/documents/:key |
ReadWrite | Apply atomic structured update expression (SET, REMOVE, ADD). |
| DELETE | /v1/tables/:name/documents/:key |
ReadWrite | Delete document with optional IF condition. |
| POST | /v1/tables/:name/query |
ReadOnly | Fast query via secondary index expression. |
| GET | /v1/tables/:name/scan |
ReadOnly | Bounded scan with pagination limits and continuation cursors. |
| POST | /v1/transactions/write |
ReadWrite | Atomic multi-document ACID write batch. |
| GET | /v1/streams |
ReadOnly | Real-time Change Data Capture (CDC) Server-Sent Events stream. |
| POST | /v1/auth/keys |
Admin | Generate 256-bit CSPRNG scoped API key. |
| DELETE | /v1/auth/keys/:id |
Admin | Instantly revoke an API key. |
| POST | /v1/admin/restore-pitr |
Admin | Roll back database to exact historical timestamp. |
| POST | /v1/admin/checkpoint |
Admin | Flush in-memory database to disk and reset WAL. |
Benchmarks & Performance Specifications
| Operation | Throughput | Average Latency | Hardware Specification |
|---|---|---|---|
| In-Memory Point Reads (L1 Cache) | 150,000+ ops/sec | 0.006 ms | 1 vCPU / 512MB RAM |
| Concurrent WAL Writes | 15,000+ ops/sec | 0.065 ms | NVMe SSD Storage |
| Concurrent HTTP REST PUT/GET | 4,068 req/sec | 0.246 ms | Pre-warmed Worker Pool |
| LSM Bloom Filter Rejection | 1,000,000+ checks/sec | 0.001 ms | Zero false negatives |