D1: Cloudflare’s First SQL Database for Workers

Cloudflare Workers launched in 2017, giving developers compute at the network edge. But most real-world applications are stateful, so the platform has steadily added storage options: KV, Durable Objects, and R2. Now Cloudflare is filling the relational gap with D1, its first SQL database, built on SQLite.

SQLite is both the most widely deployed database in the world and, arguably, the original serverless database—long before that term became associated with cloud services. For a platform like Workers that runs between server and client and draws inspiration from client-side technology, SQLite is a natural fit.

Beta access begins as early as June, with sign-ups open now.

Northwind Traders: A Live Demo

To show what D1 can do, Cloudflare has published a working demo at northwind.d1sql.com. The demo is built on the Northwind Traders sample database—the standard tutorial dataset Microsoft shipped with Access starting in 1997. It’s a typical business application schema with many foreign keys across multiple tables, making it a realistic test of relational queries.

BLOG-1074 Embedded Image - cypvvG

The demo includes a dashboard that exposes details and metrics about the D1 queries running behind the scenes, so you can see the database in action as you explore the data.

What Can You Build with D1?

Northwind Traders is a stand-in for the kind of software most organizations run somewhere. Relational databases underpin everything from ecommerce and accounting to SaaS and CRM systems. Cloudflare’s own dashboard, for example, relies on a SQL database with tables, views, and stored procedures to track customer state.

D1 targets any application that needs structured queries across a full dataset, including APIs, internal dashboards, and admin tools. You can lock those internal tools down with Cloudflare Access to restrict them to your organization.

D1 can also be combined with other Cloudflare storage and compute products, letting you build full-stack applications entirely on the Workers platform.

Developer Experience

The core of D1’s appeal is the developer workflow: moving from an empty project to a full-stack application quickly. Database creation happens in a few clicks—define tables, insert data, and you’re ready. No command memorization required.

BLOG-1074 Embedded Image - 3YSFGH

For command-line users, Wrangler 2—announced earlier this week—will include native D1 support for creating and managing databases. Attaching a database to a Worker is done through a binding on the env parameter.

export default {
  async fetch(request, env, ctx) {
    const { pathname } = new URL(request.url)
    if (pathname === '/num-products') {
      const { result } = await env.DB.get(`SELECT count(*) AS num_products FROM Product;`)
      return new Response(`There are ${result.num_products} products in the D1 database!`)
    }
  }
}

For more complex cases, you can use a Router and parameterized queries to safely pass URL parameters into SQL statements.

import { Router } from 'itty-router';
const router = Router();

router.get('/product/:id', async ({ params }, env) => {
  const { result } = await env.DB.get(
    `SELECT * FROM Product WHERE ID = $id;`,
    { $id: params.id }
  )
  return new Response(JSON.stringify(result), {
    headers: {
      'content-type': 'application/json'
    }
  })
})

export default {
  fetch: router.handle,
}

Pricing and Architecture

D1 follows Cloudflare’s storage pricing model: you pay for base storage plus database operations. Like R2, D1 charges no egress fees. Cloudflare says it will ensure D1 costs less and performs better than comparable centralized database solutions, leveraging the global network for performance and cost advantages.

Read Replication

Traditional relational databases are often monolithic, with all reads and writes flowing to a single instance because replication is hard to configure. D1 takes the opposite approach: it creates read-only replicas of your data near your users and keeps them updated automatically, handling replication configuration for you.

Batching

Applications generate multiple queries per operation. When your Worker runs near the user but the database is remote, sending queries individually over the wire is inefficient. D1’s API supports batching: any place you can send a single SQL statement, you can send an array, requiring one HTTP round-trip for multiple operations. This is suited for transactions that must execute and commit atomically.

async function recordPurchase(userId, productId, amount) { 
  const result = await env.DB.exec([
    [
      `UPDATE users SET balance = balance - $amount WHERE user_id = $user_id`,
      { $amount: amount, $user_id: userId },
    ],
    [
      'UPDATE product SET total_sales = total_sales + $amount WHERE product_id = $product_id',
      { $amount: amount, $product_id: productId },
    ],
  ])
  return result
}

Embedded Compute

Going further, D1 will allow you to define a chunk of Worker code that runs directly next to the database. Requests first hit your Worker near users but can hand off to another Worker deployed alongside a replica or the primary database instance to complete their work, giving you control and performance where it matters most.

Backups and Portability

D1 automatically saves snapshots of your database to R2 at regular intervals with one-click restoration. Since it builds on Durable Objects’ redundant storage, your database can physically relocate as needed, self-healing from failures in seconds.

Importing existing data will be supported, and SQLite’s portability means you can clone a snapshot to a local machine for development against a dedicated staging environment. Future flexibility will include spinning up a fresh database with test data for each pull request on a Pages project.

Availability

Beta invites go out starting in June 2022. Cloudflare is positioning this as the beginning of a larger effort: the first SQL database on its global network, with more capabilities to come. Documentation is available on the Cloudflare developers site.