๐Ÿ—„๏ธ Databases

Turso

Turso

A SQLite-based edge database. Uses libSQL, supports replication.

๐Ÿ“– Detailed Explanation

Turso is an SQLite-based edge distributed database developed by ChiselStrike. It uses libSQL, an open-source fork of SQLite, as its core engine, and while preserving the simplicity and compatibility of SQLite it provides modern distributed database features such as server mode, replication, and extensions. It operates database replicas at more than 35 edge locations around the world, guaranteeing millisecond-level response times from the location closest to the user.

Turso's key innovation is the Embedded Replicas feature. It keeps a local replica of the SQLite database file inside the application process, so read queries can be handled without a network round trip. Write operations are routed to the Primary database, and changes are automatically synced to all replicas. This approach brings dramatic performance improvements, especially in edge computing environments such as Vercel, Cloudflare Workers, and Fly.io.

For multi-tenancy, Turso supports the "Database per User" pattern. Creating a separate database instance for each tenant ensures data isolation and makes backup, restore, and migration of individual tenants simple. Schema Migrations can be applied simultaneously to all databases in a group, which makes it well suited to SaaS application development. Up to 500 databases per month are free, which is attractive for personal projects and startups.

In terms of developer experience, Turso supports integration with major ORMs such as Drizzle ORM, Prisma, and SQLAlchemy, and provides SDKs for many languages including TypeScript/JavaScript, Rust, Python, and Go. With the Turso CLI you can easily create databases, deploy replicas, and monitor performance. Thanks to SQLite compatibility, you can also use plain SQLite for local development and switch to Turso only in production, which simplifies setting up development and test environments.

๐Ÿ’ป Code Example

Setting up a database with the Turso CLI

# Turso CLI ์„ค์น˜
curl -sSfL https://get.tur.so/install.sh | bash

# ๋กœ๊ทธ์ธ
turso auth login

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ƒ์„ฑ (๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋ฆฌ์ „์— ์ž๋™ ๋ฐฐํฌ)
turso db create my-app-db

# ๋‹ค๋ฅธ ๋ฆฌ์ „์— ๋ณต์ œ๋ณธ ์ถ”๊ฐ€
turso db replicate my-app-db nrt  # ๋„์ฟ„
turso db replicate my-app-db icn  # ์„œ์šธ
turso db replicate my-app-db sin  # ์‹ฑ๊ฐ€ํฌ๋ฅด

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค URL ํ™•์ธ
turso db show my-app-db --url

# ์ธ์ฆ ํ† ํฐ ์ƒ์„ฑ
turso db tokens create my-app-db

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์…ธ ์ ‘์†
turso db shell my-app-db

# ๊ทธ๋ฃน ์ƒ์„ฑ (๋ฉ€ํ‹ฐํ…Œ๋„Œ์‹œ)
turso group create my-saas-group
turso db create tenant-001 --group my-saas-group
turso db create tenant-002 --group my-saas-group

Using Turso with TypeScript/Node.js

import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";
import { sql } from "drizzle-orm";

// 1. ๊ธฐ๋ณธ ํด๋ผ์ด์–ธํŠธ ์—ฐ๊ฒฐ
const client = createClient({
  url: process.env.TURSO_DATABASE_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

// 2. Embedded Replica ์„ค์ • (๋กœ์ปฌ ๋ณต์ œ๋ณธ์œผ๋กœ ์ฝ๊ธฐ ์ตœ์ ํ™”)
const clientWithReplica = createClient({
  url: process.env.TURSO_DATABASE_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN,
  syncUrl: process.env.TURSO_DATABASE_URL,  // ๋™๊ธฐํ™” ๋Œ€์ƒ
  syncInterval: 60,  // 60์ดˆ๋งˆ๋‹ค ์ž๋™ ๋™๊ธฐํ™”
});

// ์ˆ˜๋™ ๋™๊ธฐํ™” ํŠธ๋ฆฌ๊ฑฐ
await clientWithReplica.sync();

// 3. ๊ธฐ๋ณธ ์ฟผ๋ฆฌ ์‹คํ–‰
async function basicQueries() {
  // ํ…Œ์ด๋ธ” ์ƒ์„ฑ
  await client.execute(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      email TEXT UNIQUE NOT NULL,
      name TEXT NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // ๋ฐ์ดํ„ฐ ์‚ฝ์ž… (Prepared Statement)
  const result = await client.execute({
    sql: "INSERT INTO users (email, name) VALUES (?, ?)",
    args: ["user@example.com", "ํ™๊ธธ๋™"],
  });
  console.log("Inserted ID:", result.lastInsertRowid);

  // ๋ฐฐ์น˜ ์‚ฝ์ž… (ํŠธ๋žœ์žญ์…˜)
  await client.batch([
    { sql: "INSERT INTO users (email, name) VALUES (?, ?)", args: ["a@test.com", "์‚ฌ์šฉ์žA"] },
    { sql: "INSERT INTO users (email, name) VALUES (?, ?)", args: ["b@test.com", "์‚ฌ์šฉ์žB"] },
    { sql: "INSERT INTO users (email, name) VALUES (?, ?)", args: ["c@test.com", "์‚ฌ์šฉ์žC"] },
  ], "write");

  // ๋ฐ์ดํ„ฐ ์กฐํšŒ
  const users = await client.execute("SELECT * FROM users LIMIT 10");
  for (const row of users.rows) {
    console.log(`${row.id}: ${row.name} (${row.email})`);
  }
}

// 4. Drizzle ORM๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉ
import { integer, text, sqliteTable } from "drizzle-orm/sqlite-core";

const users = sqliteTable("users", {
  id: integer("id").primaryKey({ autoIncrement: true }),
  email: text("email").notNull().unique(),
  name: text("name").notNull(),
  createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`),
});

const db = drizzle(client, { schema: { users } });

async function drizzleQueries() {
  // ์‚ฝ์ž…
  await db.insert(users).values({
    email: "drizzle@test.com",
    name: "Drizzle User",
  });

  // ์กฐํšŒ with ์กฐ๊ฑด
  const results = await db
    .select()
    .from(users)
    .where(sql`name LIKE ${"ํ™%"}`);

  return results;
}

// 5. ํŠธ๋žœ์žญ์…˜ ์ฒ˜๋ฆฌ
async function transferCredits(fromId: number, toId: number, amount: number) {
  const transaction = await client.transaction("write");

  try {
    await transaction.execute({
      sql: "UPDATE accounts SET credits = credits - ? WHERE id = ?",
      args: [amount, fromId],
    });

    await transaction.execute({
      sql: "UPDATE accounts SET credits = credits + ? WHERE id = ?",
      args: [amount, toId],
    });

    await transaction.commit();
    console.log("Transfer successful");
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
}

Using Turso with the Next.js App Router

// lib/turso.ts - Turso ํด๋ผ์ด์–ธํŠธ ์„ค์ •
import { createClient } from "@libsql/client/web";

export const turso = createClient({
  url: process.env.TURSO_DATABASE_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

// app/api/users/route.ts - API Route
import { NextRequest, NextResponse } from "next/server";
import { turso } from "@/lib/turso";

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const page = parseInt(searchParams.get("page") || "1");
  const limit = 20;
  const offset = (page - 1) * limit;

  const result = await turso.execute({
    sql: "SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?",
    args: [limit, offset],
  });

  const countResult = await turso.execute("SELECT COUNT(*) as total FROM users");
  const total = countResult.rows[0].total as number;

  return NextResponse.json({
    users: result.rows,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
    },
  });
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  const { email, name } = body;

  try {
    const result = await turso.execute({
      sql: "INSERT INTO users (email, name) VALUES (?, ?)",
      args: [email, name],
    });

    return NextResponse.json({
      id: result.lastInsertRowid,
      message: "User created"
    }, { status: 201 });
  } catch (error: any) {
    if (error.message.includes("UNIQUE constraint")) {
      return NextResponse.json({ error: "Email already exists" }, { status: 409 });
    }
    throw error;
  }
}

// app/users/page.tsx - Server Component
import { turso } from "@/lib/turso";

interface User {
  id: number;
  email: string;
  name: string;
  created_at: string;
}

export default async function UsersPage() {
  const result = await turso.execute("SELECT * FROM users ORDER BY created_at DESC LIMIT 50");
  const users = result.rows as unknown as User[];

  return (
    

์‚ฌ์šฉ์ž ๋ชฉ๋ก

    {users.map((user) => (
  • {user.name} ({user.email})
  • ))}
); }

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "I looked into adopting Turso to cut API latency at the edge, and combined with Vercel Edge Functions it comes in under 50ms."
  • "If you turn on Embedded Replica, reads are handled locally, so you can query even without a database connection."
  • "When implementing SaaS multi-tenancy, the Database per User pattern is convenient, and Turso's free plan supports up to 500 DBs, so it's no burden early on."
  • "Since it's based on libSQL, we could use our existing SQLite migration tools as they are, so the switch was easy."
  • "Turso is an edge distributed database based on libSQL, an open-source fork of SQLite. It operates replicas at edge locations around the world to provide ultra-low-latency responses."
  • "Embedded Replicas is an architecture that keeps an SQLite file locally inside the app process, handles reads without a network round trip, and routes only writes to the Primary."
  • "Unlike plain SQLite, Turso supports remote access over HTTP, multi-region replication, and server mode, so it can be used in distributed environments."
  • "In multi-tenancy scenarios, you can easily create and delete an independent DB for each tenant, and apply schema migrations in bulk at the group level."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "A syncInterval of 60 seconds is fine for data that isn't real-time, but for sensitive data like inventory it would be better to add a manual sync() call."
  • "For batch jobs, using client.batch() reduces round trips. It's much faster than running execute 10 times individually."
  • "If you use sqliteTable in your Drizzle schema, it's compatible with both Turso and local SQLite, which makes setting up a test environment easier."
  • "You must specify the transaction type as 'write' for it to be routed to the Primary. The default is 'read', so writes can fail."

โš ๏ธ Cautions

๐Ÿ”— Related Terms

๐Ÿ“š Learn More