Turso
Turso
A SQLite-based edge database. Uses libSQL, supports replication.
Turso
A SQLite-based edge database. Uses libSQL, supports replication.
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.
# 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
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;
}
}
// 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})
))}
);
}
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free