Bun nativo: SQLite + Redis client built-in
Bun runtime provides native drivers for SQLite and Redis directly integrated into the core, eliminating the need for external dependencies for the most common databases. This article explores how to leverage these built-in clients to build performant server-side applications, with real-world code examples and best practices for managing distributed caching and data persistence.
1. Introduction to Bun and native databases
Bun is a JavaScript/TypeScript runtime designed for speed, with a focus on intuitive developer experience and production performance. Unlike Node.js, which requires npm packages for every database operation, Bun includes native drivers for the most commonly used databases: SQLite for local persistence and Redis for distributed caching.
Native integration means zero marshalling overhead, zero npm dependencies, and zero versioning mismatch — the driver is part of the runtime itself, tested and optimized by the Bun core team.
2. Native SQLite in Bun
SQLite is an embedded database perfect for monolithic applications and microservices that need local persistence without a separate resource. Bun integrates it as a built-in module, accessible via the Bun.sql API.
2.1 Initial setup and connection
No installation required. The SQLite module is available directly in Bun 1.0+.
import { sql } from "bun";
// Open database (file-based)
const db = sql({
filename: "./data.sqlite",
});
// Test operation
const version = db.query("SELECT sqlite_version() as version").all();
console.log("SQLite version:", version);
// In-memory database (for tests)
const memDb = sql();
2.2 Queries and CRUD operations
Queries in Bun use a syntax similar to other SQL drivers, with support for template literals and safe parameters.
import { sql } from "bun";
const db = sql({ filename: "./app.sqlite" });
// CREATE TABLE
db.query(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`).run();
// INSERT with parameters
const insertUser = db.query("INSERT INTO users (name, email) VALUES (?, ?)");
insertUser.run("Alice", "alice@example.com");
insertUser.run("Bob", "bob@example.com");
// SELECT all
const users = db.query("SELECT * FROM users").all();
console.log("Users:", users);
// SELECT with WHERE
const user = db.query("SELECT * FROM users WHERE email = ?").get("alice@example.com");
console.log("User:", user);
// UPDATE
db.query("UPDATE users SET name = ? WHERE email = ?").run("Alice Smith", "alice@example.com");
// DELETE
db.query("DELETE FROM users WHERE id = ?").run(1);
2.3 Prepared statements and parameter binding
Prepared statements protect against SQL injection and improve performance for repeated queries.
import { sql } from "bun";
const db = sql({ filename: "./app.sqlite" });
// Reusable prepared statement
const findUserById = db.query("SELECT * FROM users WHERE id = ?");
// Different bindings
const user1 = findUserById.get(1);
const user2 = findUserById.get(2);
// Transactions
const transaction = db.transaction(() => {
db.query("INSERT INTO users (name, email) VALUES (?, ?)").run("Charlie", "charlie@example.com");
db.query("INSERT INTO users (name, email) VALUES (?, ?)").run("Diana", "diana@example.com");
return true;
});
const result = transaction();
console.log("Transaction completed:", result);
3. Built-in Redis client in Bun
Bun integrates a high-performance Redis client via the Bun.redis API. Perfect for caching, session storage, and distributed pub/sub messaging.
3.1 Redis connection
Redis must be running on localhost:6379 by default, or you can specify a custom connection URL.
import { redis } from "bun";
// Connection to local Redis server
const client = await redis({
url: "redis://localhost:6379",
});
// Or use default
const defaultClient = await redis();
// Verify connection
const pong = await client.ping();
console.log("Redis ping:", pong); // Output: "PONG"
3.2 Basic operations: GET, SET, EXPIRE
Standard Redis operations are supported with intuitive syntax.
import { redis } from "bun";
const client = await redis();
// SET with TTL
await client.set("user:1:profile", JSON.stringify({ name: "Alice", email: "alice@ex.com" }), {
ex: 3600, // TTL of 1 hour
});
// GET
const profile = await client.get("user:1:profile");
console.log("Profile:", JSON.parse(profile));
// DEL
await client.del("user:1:profile");
// INCR (counters)
const visits = await client.incr("page:home:visits");
console.log("Page home visits:", visits);
// LPUSH / LPOP (queues)
await client.lpush("queue:tasks", "task-1", "task-2", "task-3");
const task = await client.lpop("queue:tasks");
console.log("Processed task:", task);
3.3 Pub/Sub for distributed messaging
Redis pub/sub enables real-time communication between services and clients.
import { redis } from "bun";
// Subscriber
const subscriber = await redis();
await subscriber.subscribe("notifications", "alerts", (message, channel) => {
console.log(`[${channel}]: ${message}`);
});
// Publisher (in another process/worker)
const publisher = await redis();
// Publish messages
await publisher.publish("notifications", "User Alice logged in");
await publisher.publish("alerts", "Database connection error");
4. Pattern: Cache with SQLite fallback
A common pattern combines Redis for fast caching with SQLite as a local fallback or for long-term persistence.
import { sql, redis } from "bun";
const db = sql({ filename: "./app.sqlite" });
const cache = await redis();
// Lookup function with cache
async function getUserProfile(userId) {
// 1. Try Redis cache
const cached = await cache.get(`user:${userId}:profile`);
if (cached) {
console.log("Cache hit");
return JSON.parse(cached);
}
// 2. Fallback: read from SQLite
const user = db.query("SELECT * FROM users WHERE id = ?").get(userId);
if (!user) {
return null;
}
// 3. Populate cache for next request
await cache.set(`user:${userId}:profile`, JSON.stringify(user), {
ex: 1800, // 30 minutes
});
console.log("Database hit, cache populated");
return user;
}
// Usage
const profile = await getUserProfile(1);
console.log("User profile:", profile);
5. Benchmark: Bun SQLite vs Node.js
Bun's native drivers offer significant performance improvements over npm bindings on Node.js.
import { sql } from "bun";
import { performance } from "perf_hooks";
const db = sql({ filename: "./bench.sqlite" });
// Setup
db.query(`
DROP TABLE IF EXISTS bench_data;
CREATE TABLE bench_data (
id INTEGER PRIMARY KEY,
value TEXT NOT NULL
);
`).run();
// Benchmark: 10,000 inserts
const start = performance.now();
for (let i = 0; i < 10000; i++) {
db.query("INSERT INTO bench_data (value) VALUES (?)").run(`value-${i}`);
}
const insertTime = performance.now() - start;
console.log(`10,000 inserts: ${insertTime.toFixed(2)}ms`);
// Benchmark: 10,000 selects
const selectStart = performance.now();
for (let i = 0; i < 10000; i++) {
db.query("SELECT * FROM bench_data WHERE id = ?").get(i + 1);
}
const selectTime = performance.now() - selectStart;
console.log(`10,000 selects: ${selectTime.toFixed(2)}ms`);
6. Best practices for SQLite and Redis in production
6.1 Timeout and retry management
Remote connections (Redis) can fail. Implement retry logic with exponential backoff.
async function redisWithRetry(operation, maxRetries = 3) {
let attempt = 0;
while (attempt < maxRetries) {
try {
return await operation();
} catch (error) {
attempt++;
if (attempt >= maxRetries) throw error;
const delayMs = Math.pow(2, attempt) * 100;
console.warn(`Attempt ${attempt}/${maxRetries}, retrying in ${delayMs}ms...`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
}
// Usage
const result = await redisWithRetry(() => cache.get("key"));
6.2 Pooling and resource management
For file-based SQLite, Bun automatically manages file locking. For Redis in cluster mode, consider connection pooling libraries.
// Singleton for Redis connection (best practice)
let redisClient = null;
async function getRedisClient() {
if (!redisClient) {
redisClient = await redis({
url: Bun.env.REDIS_URL || "redis://localhost:6379",
});
}
return redisClient;
}
// Use throughout the app
const cache = await getRedisClient();
6.3 Monitoring and logging
Track slow queries and connection errors for diagnostics.
import { sql, redis } from "bun";
const db = sql({ filename: "./app.sqlite" });
function withLogging(fn, label) {
return (...args) => {
const start = performance.now();
try {
const result = fn(...args);
const elapsed = performance.now() - start;
if (elapsed > 100) {
console.warn(`[SLOW] ${label}: ${elapsed.toFixed(2)}ms`);
}
return result;
} catch (error) {
console.error(`[ERROR] ${label}:`, error.message);
throw error;
}
};
}
// Wrap query with logging
const slowQuery = withLogging(
(userId) => db.query("SELECT * FROM users WHERE id = ?").get(userId),
"getUserById"
);
7. Common troubleshooting
7.1 "database is locked" in SQLite
Occurs when multiple processes access the file simultaneously. Solution: enable WAL (Write-Ahead Logging) mode.
import { sql } from "bun";
const db = sql({ filename: "./app.sqlite" });
// Enable WAL
db.query("PRAGMA journal_mode=WAL;").run();
// Increase lock timeout
db.query("PRAGMA busy_timeout=5000;").run(); // 5 seconds
7.2 Redis connection refused
Verify that Redis is running: redis-cli ping should respond with "PONG".
import { redis } from "bun";
async function testRedisConnection() {
try {
const client = await redis({
url: "redis://localhost:6379",
});
const pong = await client.ping();
console.log("✓ Redis connected:", pong);
} catch (error) {
console.error("✗ Redis unreachable:", error.message);
}
}
testRedisConnection();
7.3 Memory leak with Redis pub/sub
Subscribers must be explicitly unsubscribed when no longer needed.
import { redis } from "bun";
const subscriber = await redis();
const unsubscribe = await subscriber.subscribe("channel", (msg) => {
console.log("Message:", msg);
});
// Cleanup
unsubscribe(); // Terminate the subscription
8. Roadmap: what to expect from Bun 2.0+
The Bun team continues to expand native database support. Future versions will likely include built-in PostgreSQL client and drivers for other NoSQL databases. For now, SQLite and Redis cover 90% of the common use cases for modern backend applications.
9. Conclusion
Bun's native drivers for SQLite and Redis represent a quantum leap in developer experience for server-side JavaScript/TypeScript. Zero dependencies, high performance, and intuitive API make Bun a compelling choice for new backend projects and microservices. Combine these two databases to build scalable architectures: SQLite for local persistence and Redis for distributed caching and real-time messaging.
FAQ
Q: Can I use Bun SQLite in multi-process applications?
A: Yes, with WAL mode (Write-Ahead Logging). It disables explicit file locking and allows multiple concurrent readers. For high-concurrency writes, consider Redis as primary store.
Q: What is the maximum throughput for Redis in Bun?
A: The Bun Redis client achieves ~100k op/s on a single connection. For higher throughput, use connection pooling or replicate Redis.
Q: Does Bun SQLite support migrations?
A: Not natively. Use an external tool like Flyway or create a custom one by running SQL scripts at boot. Schema is completely under your control.
Q: How do I configure Redis with authentication in Bun?
A: Pass the password in the URL: redis://default:password@host:6379, or use environment variables.
Q: Does the Bun SQLite driver support encryption?
A: Native SQLite in Bun does not include built-in encryption. Use external SQLCipher or encrypt the file with operating system tools.

Commenti
Caricamento commenti...
Sign in to comment