iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎲

Comparing Cloudflare D1 and SQLite storage in Durable Objects

に公開
2025/05/11

Cloudflare offers two ways to handle SQLite-based databases.

  • Cloudflare D1
  • SQLite storage in Durable Object

The former is a full-managed SQLite-based database service that launched with significant attention as the first product to allow database handling on Cloudflare. A key feature is that while it builds the database as SQLite, being a Cloudflare product, it lacks the concept of regions and allows you to handle the database globally.
Later on, functionality to directly place and handle SQLite within a Durable Object became available. The latter is more of a product that strips away the full-managed features of D1 to allow direct use of SQLite. (My impression is that it feels like the internal implementation was made open.)
Furthermore, with the addition of a free tier for Durable Objects during the recent Developer Week in April 2025, the barrier to entry has lowered. Therefore, I believe it's worth re-examining the differences between D1 and SQLite storage in Durable Object.

Usage differences on Cloudflare Workers

First, there are differences in usage. My impression is that SQLite storage in Durable Object has a more idiosyncratic way of being used. Let's look at some code for fetching simple data.
First, the code using D1.

wrangler.jsonc
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  ...
  "d1_databases": [
    {
      "binding": "DB",
      "database_id": "YOUR_D1_DATABASE_ID",
      "database_name": "your_database_name",
    }
  ],
}
src/index.ts
export interface Env {
  DB: D1Database;
}

export default {
  async fetch(request, env): Promise<Response> {
    const { results } = await env.DB.prepare(
      "SELECT * FROM Users WHERE name = ?",
    )
      .bind("tom")
      .all();
    return Response.json(results);
  },
} satisfies ExportedHandler<Env>;

This code retrieves data where name is tom from the Users table. To set D1 in an environment variable named DB, you can easily use it by describing it in wrangler.jsonc or similar.
Next, let's look at the code using SQLite storage in Durable Object.

wrangler.jsonc
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  ...
  "durable_objects": {
    "bindings": [
      {
        "name": "YOUR_DURABLE_OBJECT_NAME",
        "class_name": "YourDurableObjectClassName"
      }
    ]
  },
  "migrations": [
    {
      "tag": "v1",
      "new_sqlite_classes": ["YourDurableObjectClassName"]
    }
  ]
}
src/index.ts
export interface Env {
  YOUR_DURABLE_OBJECT_NAME: DurableObjectNamespace<import("./src/index").YourDurableObjectClassName>;
}

export class YourDurableObjectClassName extends DurableObject {
  sql: SqlStorage;

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.sql = ctx.storage.sql;

    ctx.blockConcurrencyWhile(async () => {
      await this._migrate();
    });
  }

  getUsers() {
    const cursor = this.sql.exec(
      "SELECT * FROM Users WHERE name = ?",
      "tom",
    )

    return { results: cursor.toArray() }
  }

  async _migrate() {
    this.sql.exec(`CREATE TABLE IF NOT EXISTS "Users" (
id INTEGER PRIMARY KEY NOT NULL,
username TEXT NOT NULL,
email TEXT NOT NULL
);`
    );
  }
}

export default {
  async fetch(request, env): Promise<Response> {
    const id = c.env.CHECK_SQLITE_DURABLE_OBJECT.idFromName("db");
    const stub = c.env.CHECK_SQLITE_DURABLE_OBJECT.get(id);

    const { results } = stub.getUsers();
    return Response.json(results);
  },
} satisfies ExportedHandler<Env>;

What do you think at first glance? You can see that the usage changes significantly compared to D1. In SQLite storage in Durable Object, a class declaration called DurableObject appears for using Durable Objects. Also, a major difference from D1 is that you cannot directly execute DML to manipulate the DB from the fetch function.

src/index.ts
export class YourDurableObjectClassName extends DurableObject {
  sql: SqlStorage;

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.sql = ctx.storage.sql;
  }

  get db() {
    return this.sql // Cannot return
  }
}

export default {
  async fetch(request, env): Promise<Response> {
    const id = c.env.CHECK_SQLITE_DURABLE_OBJECT.idFromName("db");
    const stub = c.env.CHECK_SQLITE_DURABLE_OBJECT.get(id);

    const { results } = stub.db.exec("SELECT * FROM Users"); // This is not possible
  }
} satisfies ExportedHandler<Env>;

It must be implemented on the DurableObject class side. This is because the DurableObject itself is defined as something separate from the Cloudflare Workers that executes it (presumably, Durable Objects are also implemented with Cloudflare Workers), and Cloudflare Workers and Durable Objects communicate internally to exchange data.
Because data is exchanged via communication, the SQLite and its connection information held inside the Durable Object cannot be exposed to the outside; it is only possible to exchange the results of queries to SQLite within the Durable Object.

Operational Differences

Beyond the differences in execution methods, there are significant differences regarding operations. There is a big gap between "being able to use it" and "being able to operate it," and this difference becomes apparent when looking ahead to operation.

Migration methods

It's not that once a database is defined, you only need to manage the increase or decrease of data. As an application changes, the shape of the database also changes to keep up.
D1 has a command called wrangler d1 migrate and a feature to manage DDL for changing the database. By running this command, it executes SQL files in the migrations/ directory by default. Of course, wrangler d1 migrate also has a feature that ensures already executed migration files are not rerun, executing only those that haven't been applied yet. This makes changing D1 databases relatively easy.

https://developers.cloudflare.com/workers/wrangler/commands/#d1-migrations-apply

Conversely, SQLite storage in Durable Object does not have a CLI or feature to perform migrations like D1. Therefore, you must somehow migrate the SQLite database within the Durable Object yourself.
As seen in the previous sample code, there was a description like this within the DurableObject class definition.

export class YourDurableObjectClassName extends DurableObject {
  sql: SqlStorage;

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.sql = ctx.storage.sql;

    ctx.blockConcurrencyWhile(async () => {
      await this._migrate(); // Perform migration on startup
    });
  }

  ...

  async _migrate() {
    this.sql.exec(`CREATE TABLE IF NOT EXISTS "Users" (
id INTEGER PRIMARY KEY NOT NULL,
username TEXT NOT NULL,
email TEXT NOT NULL
);`
    );
  }
}

Within the blockConcurrencyWhile process, the _migrate function—specifically the DDL to create the table—is executed. This means waiting for the use of this Durable Object until this initialization is complete. So, in the previous code example, the Durable Object instance is created when a request arrives, and this migration runs when the Durable Object is instantiated—that is, during a cold start.
This is significantly different from D1 and involves several disadvantages:

  1. Database migration is not executed until an actual request arrives.
  2. While there is no problem as long as you keep using the instantiated object, a cold start will require execution time for the migration.

Since D1 migrates in advance, it is not directly related to the execution cost of Cloudflare Workers. However, that is not the case for SQLite storage in Durable Object; migration occurs only after the Cloudflare Worker is executed. It is somewhat difficult to prevent a new version of the application from deploying based on migration results. Also, since migration is performed at runtime, if an instantiated Durable Object disappears, it will be re-instantiated, and the migration process will run again at that time. In terms of migration, SQLite storage in Durable Object is quite difficult to operate.

Differences in Support Features

D1 has several convenient features for a managed database in addition to the wrangler d1 migrate command. For example, you can retrieve SQLite data from D1 using wrangler d1 export, or easily restore backed-up data through the time-travel feature with wrangler d1 time-travel.

https://developers.cloudflare.com/workers/wrangler/commands/#d1

Additionally, D1 has a feature, albeit simple, that allows you to browse the database contents on the Cloudflare console.

In this way, D1 provides the minimum features you would expect from a managed database, but Cloudflare does not provide any D1-like features for SQLite storage in Durable Object. Therefore, you must build them yourself if necessary.

Differences in Speed

There have been persistent concerns about D1's speed. So, I actually measured it, imagining that SQLite running on a Durable Object might have addressed those issues.
To measure it, I ran the code from the following repository and checked the speed under the conditions listed below.

https://github.com/chimame/check-d1-performance

  1. Time to execute DELETE on a table and then run 1,000 SQL statements, each performing 100 INSERTs (about 100,000 records) in one go.
  2. Time to execute SELECT COUNT(id) on a table.
  3. Time to retrieve data from a 100,000-record table with LIMIT 50.
  4. Time to execute the LIMIT 50 query 100 times.
  5. Time to perform a LIKE search on a column without an index.
  6. Time to execute a single INSERT once.

First, here are the results for "the time taken to issue a DELETE against the table and then execute 1,000 SQL statements, each performing 100 INSERTs as a single execution (totaling approximately 100,000 records)."

D1 SQLite storage in Durable Object
1st attempt 45,992 ms 417 ms
2nd attempt 45,609 ms 432 ms
3rd attempt 45,477 ms 453 ms
4th attempt 43,087 ms 401 ms
5th attempt 41,138 ms 427 ms

As you can see, there is a staggering difference. SQLite storage in Durable Object processes at about 100 times the speed of D1. It's at a level where you might even doubt if it's true, but since I confirmed that the number of records is returned correctly in the subsequent process for retrieving data volume, I believe the results are accurate.
Next, let's look at a very simple SQL statement: "the time taken to execute SELECT COUNT(id) on the table."

D1 SQLite storage in Durable Object
1st attempt 50 ms 29 ms
2nd attempt 38 ms 26 ms
3rd attempt 58 ms 21 ms
4th attempt 39 ms 23 ms
5th attempt 90 ms 26 ms

Looking at this, SQLite storage in Durable Object is indeed faster for reads as well, but the result is about twice as fast rather than the 100-fold difference seen earlier. Even so, "twice as fast" is formidable.
Next, instead of a count, let's look at the actual data retrieval SQL: "the time taken to execute SQL to retrieve data from a 100,000-record table with LIMIT 50."

D1 SQLite storage in Durable Object
1st attempt 55 ms 19 ms
2nd attempt 37 ms 19 ms
3rd attempt 33 ms 21 ms
4th attempt 50 ms 21 ms
5th attempt 40 ms 16 ms

D1 shows no significant difference from the time taken for the count retrieval earlier, but SQLite storage in Durable Object is slightly faster. As a result, the gap with D1 appears to have widened to about 2.5 times.

To look into it a bit more, let's examine the speed by issuing SQL that executes that query 100 times.

D1 SQLite storage in Durable Object
1st attempt 3,580 ms 41 ms
2nd attempt 3,709 ms 44 ms
3rd attempt 3,165 ms 46 ms
4th attempt 3,457 ms 45 ms
5th attempt 3,128 ms 41 ms

This is a startling result. D1's execution speed builds up significantly as the number of executions increases, though not strictly proportionally. However, for SQLite storage in Durable Object, the processing time barely accumulates, and it's only about twice as long as the time for a single execution. Honestly, I don't know what's going on.

Finally, as a read query, let's look at the "time taken to execute a LIKE search on a column without an index".

D1 SQLite storage in Durable Object
1st attempt 84 ms 30 ms
2nd attempt 93 ms 33 ms
3rd attempt 53 ms 33 ms
4th attempt 86 ms 38 ms
5th attempt 73 ms 35 ms

Both see a slight increase in processing time, but even then, you can see that the speed degradation for SQLite storage in Durable Object is minimal.

Lastly, to look at writes, let's examine the "time taken to execute a single INSERT once".

D1 SQLite storage in Durable Object
1st attempt 55 ms 31 ms
2nd attempt 49 ms 29 ms
3rd attempt 44 ms 26 ms
4th attempt 43 ms 27 ms
5th attempt 40 ms 29 ms

The processing time increases slightly compared to reads. However, when compared to the initial results for executing SQL to insert large amounts of data, the speed of SQLite storage in Durable Object is at a level that is honestly unfathomable.

As shown, SQLite storage in Durable Object is significantly faster than D1. I suppose this is because it provides raw SQLite with various overheads stripped away compared to D1.

Pricing Differences

The pricing for D1 and SQLite storage in Durable Object seems to be the same. However, as of May 11, 2025, the SQLite-specific pricing plan for SQLite storage in Durable Object has not yet taken effect, and it appears to basically follow the standard Durable Object pricing.

https://developers.cloudflare.com/d1/platform/pricing/

https://developers.cloudflare.com/durable-objects/platform/pricing/#sqlite-storage-backend

Workers Free Plan Workers Paid Plan
Reads 5 million/day First 25 billion/month (Free) + $0.001/1 million rows
Writes 100,000/day First 50 million/month (Free) + $1.00/1 million rows
Storage 5 GB First 5 GB (Free) + $0.75 per GB/month

Looking at this alone, I think it's an exceptional price. Currently, since SQLite storage in Durable Object uses the same settings as regular Durable Objects, you can process 100,000 operations per day (combined read/write) for free on the Free plan.

Summary

Certainly, SQLite storage in Durable Object is significantly faster than D1, which had some speed concerns. However, it lacks the features one would expect from a managed database like D1. While using SQLite storage in Durable Object is an option if you can manage it yourself, it might be realistically difficult.
Although D1 has a certain range of features, its speed—specifically regarding cold starts—presents some difficulties, making it hard to wholeheartedly adopt it in every scenario.
For now, I believe the best approach is to use each for specific purposes where you can tolerate their respective drawbacks.

Discussion