Salta al contenuto principale

Bun nativo: SQLite + Redis client built-in

I client SQLite e Redis integrati in Bun: uso nativo, pattern di cache con fallback su SQLite, benchmark contro Node.js e buone pratiche in produzione.

Cosa ne pensi di questo articolo?

Bun nativo: SQLite + Redis client built-in
Bun Runtime 2027Foto:Ruben BoekelooPexels

In Breve

I client SQLite e Redis integrati in Bun: uso nativo, pattern di cache con fallback su SQLite, benchmark contro Node.js e buone pratiche in produzione.

Bun nativo: SQLite + Redis client built-in

Bun runtime offre driver nativi per SQLite e Redis direttamente integrati nel core, eliminando la necessità di dipendenze esterne per i database più comuni. Questo articolo esplora come sfruttare questi client built-in per costruire applicazioni server-side performanti, con esempi di codice reale e best practice per la gestione di cache distribuita e persistenza dati.

1. Introduzione a Bun e i database nativi

Bun è un runtime JavaScript/TypeScript progettato per la velocità, con focus su un'esperienza di sviluppo intuitiva e performance di produzione. A differenza di Node.js, che richiede pacchetti npm per ogni operazione database, Bun include driver nativi per i database più usati: SQLite per la persistenza locale e Redis per il caching distribuito.

L'integrazione nativa significa zero overhead di marshalling, zero dipendenze npm e zero versioning mismatch — il driver è parte del runtime stesso, testato e ottimizzato dal core team di Bun.

2. SQLite nativo in Bun

SQLite è un database embed perfetto per applicazioni monolitiche e microservizi che hanno bisogno di persistenza locale senza una risorsa separata. Bun lo integra come modulo built-in, accessibile tramite l'API Bun.sql.

2.1 Setup iniziale e connessione

Non è necessario installare nulla. Il modulo SQLite è disponibile direttamente in Bun 1.0+.


import { sql } from "bun";

// Apertura database (file-based)
const db = sql({
  filename: "./data.sqlite",
});

// Operazione di test
const version = db.query("SELECT sqlite_version() as version").all();
console.log("SQLite versione:", version);

// Database in-memory (per test)
const memDb = sql();
    

2.2 Query e operazioni CRUD

Le query in Bun usano una sintassi simile a quella di altri driver SQL, con supporto per template literal e parametri sicuri.


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 con parametri
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("Utenti:", users);

// SELECT con WHERE
const user = db.query("SELECT * FROM users WHERE email = ?").get("alice@example.com");
console.log("Utente:", 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 statement e binding parametri

I prepared statement proteggono da SQL injection e migliorano le performance per query ripetute.


import { sql } from "bun";

const db = sql({ filename: "./app.sqlite" });

// Prepared statement riusabile
const findUserById = db.query("SELECT * FROM users WHERE id = ?");

// Bind diversi
const user1 = findUserById.get(1);
const user2 = findUserById.get(2);

// Transazioni
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("Transazione completata:", result);
    

3. Redis client built-in in Bun

Bun integra un client Redis ad alta performance tramite l'API Bun.redis. Perfetto per caching, session storage e pub/sub messaging distribuito.

3.1 Connessione a Redis

Redis deve essere in esecuzione su localhost:6379 di default, oppure specificare l'URL di connessione.


import { redis } from "bun";

// Connessione al server Redis locale
const client = await redis({
  url: "redis://localhost:6379",
});

// Oppure default
const defaultClient = await redis();

// Verifica connessione
const pong = await client.ping();
console.log("Redis ping:", pong); // Output: "PONG"
    

3.2 Operazioni di base: GET, SET, EXPIRE

Le operazioni Redis standard sono supportate con sintassi intuitiva.


import { redis } from "bun";

const client = await redis();

// SET con TTL
await client.set("user:1:profile", JSON.stringify({ name: "Alice", email: "alice@ex.com" }), {
  ex: 3600, // TTL di 1 ora
});

// GET
const profile = await client.get("user:1:profile");
console.log("Profilo:", JSON.parse(profile));

// DEL
await client.del("user:1:profile");

// INCR (contatori)
const visits = await client.incr("page:home:visits");
console.log("Visite pagina home:", visits);

// LPUSH / LPOP (code)
await client.lpush("queue:tasks", "task-1", "task-2", "task-3");
const task = await client.lpop("queue:tasks");
console.log("Task processato:", task);
    

3.3 Pub/Sub per messaging distribuito

Redis pub/sub permette comunicazione real-time tra servizi e client.


import { redis } from "bun";

// Subscriber
const subscriber = await redis();

await subscriber.subscribe("notifications", "alerts", (message, channel) => {
  console.log(`[${channel}]: ${message}`);
});

// Publisher (in un altro processo/worker)
const publisher = await redis();

// Pubblica messaggi
await publisher.publish("notifications", "User Alice logged in");
await publisher.publish("alerts", "Database connection error");
    

4. Pattern: Cache con fallback SQLite

Un pattern comune combina Redis per il caching veloce con SQLite come fallback locale o per persistenza a lungo termine.


import { sql, redis } from "bun";

const db = sql({ filename: "./app.sqlite" });
const cache = await redis();

// Funzione di lookup con cache
async function getUserProfile(userId) {
  // 1. Prova cache Redis
  const cached = await cache.get(`user:${userId}:profile`);
  if (cached) {
    console.log("Cache hit");
    return JSON.parse(cached);
  }

  // 2. Fallback: leggi da SQLite
  const user = db.query("SELECT * FROM users WHERE id = ?").get(userId);
  if (!user) {
    return null;
  }

  // 3. Popola cache per la prossima richiesta
  await cache.set(`user:${userId}:profile`, JSON.stringify(user), {
    ex: 1800, // 30 minuti
  });

  console.log("Database hit, cache popolata");
  return user;
}

// Uso
const profile = await getUserProfile(1);
console.log("Profilo utente:", profile);
    

5. Benchmark: Bun SQLite vs Node.js

I driver nativi di Bun offrono significativi miglioramenti di performance rispetto ai binding npm su 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 insert
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 insert: ${insertTime.toFixed(2)}ms`);

// Benchmark: 10.000 select
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 select: ${selectTime.toFixed(2)}ms`);
    

6. Best practice per SQLite e Redis in produzione

6.1 Gestione dei timeout e retry

Le connessioni remote (Redis) possono fallire. Implementa retry con backoff esponenziale.


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(`Tentativo ${attempt}/${maxRetries}, retry tra ${delayMs}ms...`);
      await new Promise(resolve => setTimeout(resolve, delayMs));
    }
  }
}

// Uso
const result = await redisWithRetry(() => cache.get("key"));
    

6.2 Pooling e gestione risorse

Per SQLite file-based, Bun gestisce automaticamente il file lock. Per Redis in cluster, considera library di pooling di connection.


// Singleton per la connessione Redis (best practice)
let redisClient = null;

async function getRedisClient() {
  if (!redisClient) {
    redisClient = await redis({
      url: Bun.env.REDIS_URL || "redis://localhost:6379",
    });
  }
  return redisClient;
}

// Usa in tutta l'app
const cache = await getRedisClient();
    

6.3 Monitoraggio e logging

Traccia query lente e errori di connessione per diagnostic.


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 con logging
const slowQuery = withLogging(
  (userId) => db.query("SELECT * FROM users WHERE id = ?").get(userId),
  "getUserById"
);
    

7. Troubleshooting comuni

7.1 "database is locked" in SQLite

Accade quando più processi accedono al file simultaneamente. Soluzione: usa WAL (Write-Ahead Logging) mode.


import { sql } from "bun";

const db = sql({ filename: "./app.sqlite" });

// Abilita WAL
db.query("PRAGMA journal_mode=WAL;").run();

// Aumenta timeout di lock
db.query("PRAGMA busy_timeout=5000;").run(); // 5 secondi
    

7.2 Redis connection refused

Verifica che Redis sia in esecuzione: redis-cli ping deve rispondere "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 connesso:", pong);
  } catch (error) {
    console.error("✗ Redis non raggiungibile:", error.message);
  }
}

testRedisConnection();
    

7.3 Memory leak con Redis pub/sub

I subscriber devono essere esplicitamente unsubscribed quando non servono più.


import { redis } from "bun";

const subscriber = await redis();

const unsubscribe = await subscriber.subscribe("channel", (msg) => {
  console.log("Messaggio:", msg);
});

// Cleanup
unsubscribe(); // Termina la subscription
    

8. Roadmap: cosa aspettarsi da Bun 2.0+

Il team di Bun continua a espandere il supporto database nativo. Le versioni future probabilmente includeranno PostgreSQL client built-in e driver per altri database NoSQL. Per ora, SQLite e Redis coprono il 90% dei casi di uso comuni per applicazioni backend moderne.

9. Conclusione

I driver nativi di Bun per SQLite e Redis rappresentano un salto di qualità nella developer experience per JavaScript/TypeScript server-side. Zero dipendenze, alta performance e API intuitiva rendono Bun un'opzione convincente per nuovi progetti backend e microservizi. Combina questi due database per costruire architetture scalabili: SQLite per la persistenza locale e Redis per il caching distribuito e il messaging real-time.

FAQ

D: Posso usare Bun SQLite in applicazioni multi-processo?

R: Sì, con WAL mode (Write-Ahead Logging). Disabilita il file locking esplicito e permette più lettori contemporanei. Per scritture ad alta concorrenza, considera Redis come primary store.

D: Qual è il throughput massimo per Redis in Bun?

R: Il client Bun Redis raggiunge ~100k op/s su una singola connessione. Per throughput maggiore, usa connection pooling o replica Redis.

D: Bun SQLite supporta le migrazioni?

R: No nativamente. Usa un tool esterno come Flyway o creane uno custom eseguendo script SQL al boot. Lo schema è completamente sotto il tuo controllo.

D: Come configuro Redis con autenticazione in Bun?

R: Passa la password nell'URL: redis://default:password@host:6379, oppure usa variabili d'ambiente.

D: Il driver Bun SQLite supporta encryption?

R: SQLite nativo in Bun non include crittografia integrata. Usa SQLCipher esterno o crittografa il file con tool del sistema operativo.

Commenti

Caricamento commenti...

Accedi per commentare

Discuti questo articolo nella community

Unisciti al gruppo Telegram per discutere con altri sviluppatori, fare domande e condividere le tue esperienze.

Ti è piaciuto questo articolo?

Esplora altri contenuti sul blog o scopri i miei progetti