You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
description: Use D1 Sessions API to leverage read replication.
4
+
products:
5
+
- d1
6
+
date: 2025-04-04
7
+
---
8
+
9
+
D1 read replication is available in public beta to help lower average latency and increase overall throughput for read-heavy applications like e-commerce websites or content management tools.
10
+
11
+
Workers can leverage read-only database copies, called read replicase, by using D1 [Sessions API](/d1/best-practices/read-replication). A Session encapsulates all the queries from one logical session for your application. For example, a Session may correspond to all queries coming from a particular web browser session. With Sessions API, D1 queries in a Session are guanranteed to be sequentially consistent(/d1/best-practices/read-replication/#replica-lag-and-consistency-model) to avoid data consistency pitfalls. D1 [bookmarks](/d1/reference/time-travel/#bookmarks) can be used from a previous Session to ensure logical consistency between Sessions.
12
+
13
+
```ts
14
+
// retrieve bookmark from previous Session stored in HTTP header
Read replicas are automatically created by Cloudlfare (currently one in each supported [D1 region](/d1/best-practices/read-replication/#read-replica-locations)), are active/inactive based on query traffic, and are transparently routed to by Cloudflare at no additional cost.
26
+
27
+
To checkout D1 read replication:
28
+
29
+
Deploy the following Worker code using Sessions API, which will prompt you to create a D1 database and enable read replication on said database.
30
+
31
+
[](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/templates/tree/staging/d1-starter-sessions-api)
32
+
33
+
To read more about how read replication was implemented, read our [blog post](https://blog.cloudflare.com/d1-read-replication-beta)
@@ -12,26 +12,11 @@ D1 read replication can lower latency for read queries and scale read throughput
12
12
13
13
Your application can use read replicas with D1 [Sessions API](/d1/worker-api/d1-database/#withsession). A Session encapsulates all the queries from one logical session for your application. For example, a Session may correspond to all queries coming from a particular web browser session. All queries within a Session read from a database instance which is as up-to-date as your query needs it to be. Sessions API ensures [sequential consistency](/d1/best-practices/read-replication/#replica-lag-and-consistency-model) for all queries in a Session.
14
14
15
-
To checkout D1 read replication and Sessions API:
15
+
To checkout D1 read replication:
16
16
17
-
1.Deploy the following Worker code, which will prompt you to create a D1 database.
17
+
Deploy the following Worker code using Sessions API, which will prompt you to create a D1 database and enable read replication on said database.
18
18
19
-
[](https://deploy.workers.cloudflare.com/?url=https://github.com/lambrospetrou/d1-starter-sessions-api)
20
-
21
-
2. Enable read replication on the just created D1 database.
22
-
23
-
```curl
24
-
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
25
-
-H "Authorization: Bearer $TOKEN" \
26
-
-H "Content-Type: application/json" \
27
-
-d '{"read_replication": {"mode": "auto"}}'
28
-
```
29
-
30
-
:::note
31
-
To use REST API, you need to have an API token with `D1:Edit` permission.
32
-
33
-
If you do not have an API token, follow the guide: [Create API token](/fundamentals/api/get-started/create-token/).
34
-
:::
19
+
[](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/templates/tree/staging/d1-starter-sessions-api)
@@ -189,116 +174,25 @@ All write queries are still forwarded to the primary database instance. Read rep
189
174
| Primary database instance | The database instance containing the “original” copy of the database | Can serve write queries | Can serve read queries |
190
175
| Read replica database instance | A database instance containing a copy of the original database which asynchronously receives updates from the primary database instance | Forwards any write queries to the primary database instance | Can serve read queries using its own copy of the database |
191
176
192
-
## Use Sessions API
193
-
194
-
By using [Sessions API](/d1/worker-api/d1-database/#withsession) for read replication, all of your queries from a single <GlossaryTooltipterm="session">Session</GlossaryTooltip> read from a version of the database which ensures sequential consistency. This ensures that the version of the database you are reading is logically consistent even if the queries are handled by different read replicas.
195
-
196
-
D1 read replication achieves this by attaching a <GlossaryTooltipterm="bookmark">bookmark</GlossaryTooltip> to each query within a Session. For more information, refer to [Bookmarks](/d1/reference/time-travel/#bookmarks).
197
-
198
-
### Enable read replication
199
-
200
-
With the REST API, set `read_replication.mode: auto` to enable read replication on a D1 database.
201
-
202
-
:::note
203
-
To use REST API, you need to have an API token with `D1:Edit` permission.
204
-
205
-
If you do not have an API token, follow the guide: [Create API token](/fundamentals/api/get-started/create-token/).
206
-
:::
207
-
208
-
<Tabs>
209
-
<TabItemlabel="cURL">
210
-
```curl
211
-
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
With the REST API, set `read_replication.mode: disabled` to disable read replication on a D1 database.
238
-
Use an [API token](/fundamentals/api/get-started/create-token/) with `D1:Edit`[permission](/fundamentals/api/reference/permissions/#account-permissions).
239
-
240
-
<Tabs>
241
-
<TabItemlabel="cURL">
242
-
```curl
243
-
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
A system with multiple read replicas located around the world improves the performance of databases:
265
180
266
-
:::note
267
-
Disabling read replication takes 24 hours for replicas to stop processing requests.
268
-
:::
181
+
- The read throughput increases by distributing load across multiple replicas. Since multiple database instances are able to serve read-only requests, your application can serve a larger number of queries at any given time.
182
+
- The query latency decreases for users located close to the read replicas. By shortening the physical distance between a the database instance and the user, read query latency decreases, resulting in a faster application.
269
183
270
-
### Check if read replication is enabled
184
+
##Use Sessions API
271
185
272
-
`GET` D1 database REST endpoint returns if read replication is enabled or disabled.
273
-
Use an [API token](/fundamentals/api/get-started/create-token/) with `D1:Read`[permission](/fundamentals/api/reference/permissions/#account-permissions).
186
+
By using [Sessions API](/d1/worker-api/d1-database/#withsession) for read replication, all of your queries from a single <GlossaryTooltipterm="session">Session</GlossaryTooltip> read from a version of the database which ensures sequential consistency. This ensures that the version of the database you are reading is logically consistent even if the queries are handled by different read replicas.
274
187
275
-
<Tabs>
276
-
<TabItemlabel="cURL">
277
-
```curl
278
-
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
279
-
-H "Authorization: Bearer $TOKEN"
280
-
```
281
-
</TabItem>
282
-
<TabItemlabel="TypeScript">
283
-
```ts
284
-
const headers =newHeaders({
285
-
"Authorization": `Bearer ${TOKEN}`
286
-
});
188
+
D1 read replication achieves this by attaching a <GlossaryTooltipterm="bookmark">bookmark</GlossaryTooltip> to each query within a Session. For more information, refer to [Bookmarks](/d1/reference/time-travel/#bookmarks).
Read replication can be enabled at the database level in the Cloudflare dashboard. Check [**<D1Database>** > **Settings**] to view if read replication is enabled.
298
193
299
-
- Check the `read_replication` property of the `result` object
300
-
-`"mode": "auto"` indicates read replication is enabled
301
-
-`"mode": "disabled"` indicates read replication is disabled
194
+
1. Go to [**Workers & Pages** > **D1**](https://dash.cloudflare.com/?to=/:account/workers/d1).
-`served_by_region` and `served_by_primary` fields are present for all D1 remote requests, regardless of whether read replication is enabled or if the Sessions API is used. On local development, `npx wrangler dev`, these fields are `undefined`.
511
405
406
+
### Enable read replication via REST API
407
+
408
+
With the REST API, set `read_replication.mode: auto` to enable read replication on a D1 database.
409
+
410
+
For this REST endpoint, you need to have an API token with `D1:Edit` permission. If you do not have an API token, follow the guide: [Create API token](/fundamentals/api/get-started/create-token/).
411
+
412
+
<Tabs>
413
+
<TabItemlabel="cURL">
414
+
```curl
415
+
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
With the REST API, set `read_replication.mode: disabled` to disable read replication on a D1 database.
442
+
443
+
For this REST endpoint, you need to have an API token with `D1:Edit` permission. If you do not have an API token, follow the guide: [Create API token](/fundamentals/api/get-started/create-token/).
444
+
445
+
:::note
446
+
Disabling read replication takes up to 24 hours for replicas to stop processing requests. Sessions API works with databases that do not have read replication enabled, so it’s safe to run code with Sessions API even after you disable replicas.
447
+
:::
448
+
449
+
<Tabs>
450
+
<TabItemlabel="cURL">
451
+
```curl
452
+
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
`GET` D1 database REST endpoint returns if read replication is enabled or disabled.
478
+
479
+
For this REST endpoint, you need to have an API token with `D1:Read` permission. If you do not have an API token, follow the guide: [Create API token](/fundamentals/api/get-started/create-token/).
480
+
481
+
<Tabs>
482
+
<TabItemlabel="cURL">
483
+
```curl
484
+
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/d1/database/{database_id}" \
- Check the `read_replication` property of the `result` object
506
+
-`"mode": "auto"` indicates read replication is enabled
507
+
-`"mode": "disabled"` indicates read replication is disabled
508
+
512
509
## Read replica locations
513
510
514
511
Currently, D1 automatically creates a read replica in [every supported region](/d1/configuration/data-location/#available-location-hints), including the region where the primary database instance is located. These regions are:
@@ -537,14 +534,14 @@ To see the impact of read replication and check the how D1 requests are processe
537
534
538
535
There are some known limitations for D1 read replication.
539
536
540
-
-TODO: smart placemet
541
-
-TBC
537
+
-Sessions API is only available via the [D1 Worker Binding](/d1/worker-api/d1-database/#withsession) and not yet available via the REST API.
538
+
-TODO: smart placement
542
539
543
540
## Background information
544
541
545
542
### Replica lag and consistency model
546
543
547
-
To account for replica lag, it is important to consider the consistency model for D1. A consistency model is a logical framework that governs how a database system serves user queries (how the data is updated and accessed) when there are multiple database instances. Different models can be useful in different use cases. Most database systems provide [read committed](https://jepsen.io/consistency/models/read-committed), [snapshot isolation](https://jepsen.io/consistency/models/snapshot-isolation), or [serializable](https://jepsen.io/consistency/models/serializable) consistency models, depending on their configuration.
544
+
To account for <GlossaryTooltipterm="replica lag"> replica lag </GlossaryTooltip>, it is important to consider the consistency model for D1. A consistency model is a logical framework that governs how a database system serves user queries (how the data is updated and accessed) when there are multiple database instances. Different models can be useful in different use cases. Most database systems provide [read committed](https://jepsen.io/consistency/models/read-committed), [snapshot isolation](https://jepsen.io/consistency/models/snapshot-isolation), or [serializable](https://jepsen.io/consistency/models/serializable) consistency models, depending on their configuration.
548
545
549
546
#### Without Sessions API
550
547
@@ -582,19 +579,12 @@ Sequential consistency has properties such as:
582
579
-**Writes follow reads**: If you read a value, then perform a write, the subsequent write must be based on the value that was just read.
583
580
-**Read my own writes**: If you write to the database, all subsequent reads will see the write.
584
581
585
-
### Benefits of read replication
586
-
587
-
A system with multiple read replicas located around the world improves the performance of databases:
588
-
589
-
- The read throughput increases by distributing load across multiple replicas. Since multiple database instances are able to serve read-only requests, your application can serve a larger number of queries at any given time.
590
-
- The query latency decreases for users located close to the read replicas. By shortening the physical distance between a the database instance and the user, read query latency decreases, resulting in a faster application.
591
-
592
582
## Supplementary information
593
583
594
584
You may wish to refer to the following resources:
595
585
596
586
- Blog: [Beta announcement & technical deep dive](https://blog.cloudflare.com/d1-read-replication-beta/)
597
587
- Blog: [Building D1: a Global Database](https://blog.cloudflare.com/building-d1-a-global-database/)
598
588
-[D1 Sessions API documentation](/d1/worker-api/d1-database#withsession)
599
-
-[Demo application]
589
+
-[D1 Sessions API starter demo](https://github.com/cloudflare/templates/tree/staging/d1-starter-sessions-api)
600
590
-[E-commerce store read replication demo](/d1/demos/#demos)
0 commit comments