Skip to content

Commit beb24fb

Browse files
committed
Sessions capitalisation edit. Adding demo to demo
page
1 parent 5caf814 commit beb24fb

File tree

4 files changed

+46
-38
lines changed

4 files changed

+46
-38
lines changed

src/content/apps/index.yaml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,4 +347,12 @@
347347
products: [Workers, D1]
348348
languages: [TypeScript]
349349
cloudflare: true
350-
updated: 2025-02-27
350+
updated: 2025-02-27
351+
- link: https://github.com/cloudflare/templates/tree/staging/d1-starter-sessions-api
352+
id: Starter code for D1 Sessions API
353+
description: An introduction to D1 Sessions API. This demo simulates purchase orders administration.
354+
tags: []
355+
products: [Workers, D1]
356+
languages: [TypeScript]
357+
cloudflare: true
358+
updated: 2025-03-31

src/content/changelog/d1/2025-04-04-d1-read-replication-beta.mdx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,25 @@ date: 2025-04-04
88

99
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.
1010

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.
11+
Workers can leverage read-only database copies, called read replicas, 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 guaranteed 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.
1212

1313
```ts
14-
// retrieve bookmark from previous Session stored in HTTP header
14+
// retrieve bookmark from previous session stored in HTTP header
1515
const bookmark = request.headers.get('x-d1-bookmark') ?? 'first-unconstrained';
1616

1717
const session = env.DB.withSession(bookmark)
1818
const result = await session
1919
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
2020
.run()
21-
// store bookmark for a future Session
21+
// store bookmark for a future session
2222
response.headers.set('x-d1-bookmark', session.getBookmark() ?? "")
2323
```
2424

25-
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. To checkout D1 read replication:
25+
Read replicas are automatically created by Cloudflare (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. To checkout D1 read replication:
2626

2727
Deploy the following Worker code using Sessions API, which will prompt you to create a D1 database and enable read replication on said database.
2828

2929
[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/templates/tree/staging/d1-starter-sessions-api)
3030

31-
To read more about how read replication was implemented, read our [blog post](https://blog.cloudflare.com/d1-read-replication-beta)
31+
To learn more about how read replication was implemented, go to our [blog post](https://blog.cloudflare.com/d1-read-replication-beta).
3232

src/content/docs/d1/best-practices/read-replication.mdx

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { GlossaryTooltip, Details, GitHubCode, APIRequest, Tabs, TabItem, TypeSc
1010

1111
D1 read replication can lower latency for read queries and scale read throughput by adding read-only database copies, called read replicas, across regions globally closer to clients.
1212

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.
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.
1414

1515
To checkout D1 read replication:
1616

@@ -29,17 +29,17 @@ export default {
2929
async fetch(request, env, ctx): Promise<Response> {
3030
const url = new URL(request.url);
3131

32-
// A. Create the Session.
33-
// When we create a D1 Session, we can continue where we left off from a previous
34-
// Session if we have that Session's last bookmark or use a constraint.
32+
// A. Create the session.
33+
// When we create a D1 session, we can continue where we left off from a previous
34+
// session if we have that session's last bookmark or use a constraint.
3535
const bookmark = request.headers.get('x-d1-bookmark') ?? 'first-unconstrained';
3636
const session = env.DB01.withSession(bookmark);
3737

3838
try {
39-
// Use this Session for all our Workers' routes.
39+
// Use this session for all our Workers' routes.
4040
const response = await withTablesInitialized(session, async () => await handleRequest(request, session));
4141

42-
// B. Return the bookmark so we can continue the Session in another request.
42+
// B. Return the bookmark so we can continue the session in another request.
4343
response.headers.set('x-d1-bookmark', session.getBookmark() ?? "");
4444

4545
return response;
@@ -66,21 +66,21 @@ async function handleRequest(request: Request, session: D1DatabaseSession) {
6666
const tsStart = Date.now();
6767

6868
if (request.method === "GET" && pathname === '/api/orders') {
69-
// C. Session read query.
69+
// C. session read query.
7070
const resp = await session.prepare('SELECT * FROM Orders').all();
7171
return Response.json(buildResponse(session, resp, tsStart));
7272

7373
} else if (request.method === "POST" && pathname === '/api/orders') {
7474
const order = await request.json<Order>();
7575

76-
// D. Session write query.
76+
// D. session write query.
7777
// Since this is a write query, D1 will transparently forward the query.
7878
await session
7979
.prepare('INSERT INTO Orders VALUES (?, ?, ?)')
8080
.bind(order.customerId, order.orderId, order.quantity)
8181
.run();
8282

83-
// E. Session read-after-write query.
83+
// E. session read-after-write query.
8484
// In order for the application to be correct, this SELECT
8585
// statement must see the results of the INSERT statement above.
8686
const resp = await session
@@ -183,20 +183,20 @@ A system with multiple read replicas located around the world improves the perfo
183183

184184
## Use Sessions API
185185

186-
By using [Sessions API](/d1/worker-api/d1-database/#withsession) for read replication, all of your queries from a single <GlossaryTooltip term="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.
186+
By using [Sessions API](/d1/worker-api/d1-database/#withsession) for read replication, all of your queries from a single <GlossaryTooltip term="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.
187187

188-
D1 read replication achieves this by attaching a <GlossaryTooltip term="bookmark">bookmark</GlossaryTooltip> to each query within a Session. For more information, refer to [Bookmarks](/d1/reference/time-travel/#bookmarks).
188+
D1 read replication achieves this by attaching a <GlossaryTooltip term="bookmark">bookmark</GlossaryTooltip> to each query within a session. For more information, refer to [Bookmarks](/d1/reference/time-travel/#bookmarks).
189189

190-
### Enable read replicaton
190+
### Enable read replication
191191

192192
Read replication can be enabled at the database level in the Cloudflare dashboard. Check **\<D1 Database\>** > **Settings** to view if read replication is enabled.
193193

194194
1. Go to [**Workers & Pages** > **D1**](https://dash.cloudflare.com/?to=/:account/workers/d1).
195-
2. Select an existing database > Settings > Enable Read Replication.
195+
2. Select an existing database > **Settings** > **Enable Read Replication**.
196196

197-
### Start a Session without constraints
197+
### Start a session without constraints
198198

199-
To create a Session from any available database version, use `withSession()` without any parameters, which will route the first query to any database instance, either the primary database instance or a read replica.
199+
To create a session from any available database version, use `withSession()` without any parameters, which will route the first query to any database instance, either the primary database instance or a read replica.
200200

201201
```ts
202202
const session = env.DB.withSession() // synchronous
@@ -207,16 +207,16 @@ const result = await session
207207
```
208208

209209
- `withSession()` is the same as `withSession("first-unconstrained")`
210-
- This approach is best when your application does not require the latest database version. All queries in a Session ensure sequential consistency.
210+
- This approach is best when your application does not require the latest database version. All queries in a session ensure sequential consistency.
211211
- Refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
212212

213-
{/* #### Example of a D1 Session without constraints
213+
{/* #### Example of a D1 session without constraints
214214
215215
Suppose you want to develop a feature for displaying “likes” on a social network application.
216216
217-
The number of likes is a good example of a situation which does not require the latest information all the time. When displaying the number of likes of a post, the first request starts a new D1 Session using the constraint `first-unconstrained`, which will be served by the nearest D1 read replica.
217+
The number of likes is a good example of a situation which does not require the latest information all the time. When displaying the number of likes of a post, the first request starts a new D1 session using the constraint `first-unconstrained`, which will be served by the nearest D1 read replica.
218218
219-
Subsequent interactions on the application should continue using the same Session by passing the `bookmark` from the first query to subsequent requests. This guarantees that all interactions will observe information at least as up-to-date as the initial request, and therefore never show information older than what a user has already observed. The number of likes will be updated with newer counts over time with subsequent requests as D1 asynchronously updates the read replicas with the changes from the primary database.
219+
Subsequent interactions on the application should continue using the same session by passing the `bookmark` from the first query to subsequent requests. This guarantees that all interactions will observe information at least as up-to-date as the initial request, and therefore never show information older than what a user has already observed. The number of likes will be updated with newer counts over time with subsequent requests as D1 asynchronously updates the read replicas with the changes from the primary database.
220220
221221
```js
222222
async function getLikes(postId: string, db: D1Database, bookmark: string | null): GetLikesResult {
@@ -231,9 +231,9 @@ async function getLikes(postId: string, db: D1Database, bookmark: string | null)
231231
}
232232
``` */}
233233

234-
### Start a Session with all latest data
234+
### Start a session with all latest data
235235

236-
To create a Session from the latest database version, use `withSession("first-primary")`, which will route the first query to the primary database instance.
236+
To create a session from the latest database version, use `withSession("first-primary")`, which will route the first query to the primary database instance.
237237

238238
```ts
239239
const session = env.DB.withSession(`first-primary`) // synchronous
@@ -243,16 +243,16 @@ const result = await session
243243
.run()
244244
```
245245

246-
- This approach is best when your application requires the latest database version. All queries in a Session ensure sequential consistency.
246+
- This approach is best when your application requires the latest database version. All queries in a session ensure sequential consistency.
247247
- Refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
248248

249249
{/* #### Example of using `first-primary`
250250
251251
Suppose you want to develop a webpage for an electricity provider which lists the electricity bill statements. An assumption here is that each statement is immutable. Once issued, it never changes.
252252
253-
In this scenario, you want the first request of the page to show a list of all the statements and their issue dates. Therefore, the first request starts a new D1 Session using the constraint `first-primary` to get the latest information (ensuring that the list includes all issued bill statements) from the primary database instance.
253+
In this scenario, you want the first request of the page to show a list of all the statements and their issue dates. Therefore, the first request starts a new D1 session using the constraint `first-primary` to get the latest information (ensuring that the list includes all issued bill statements) from the primary database instance.
254254
255-
Then, when opening an individual electricity bill statement, we can continue using the same Session by passing the `bookmark` from the first query to subsequent requests. Since each bill statement is immutable, any bill statement listed from the first query is guaranteed to be available in subsequent requests using the same Session.
255+
Then, when opening an individual electricity bill statement, we can continue using the same session by passing the `bookmark` from the first query to subsequent requests. Since each bill statement is immutable, any bill statement listed from the first query is guaranteed to be available in subsequent requests using the same session.
256256
257257
```ts
258258
async function listBillStatements(accountId: string, db: D1Database): Promise<ListBillStatementsResult> {
@@ -275,23 +275,23 @@ async function getBillStatement(accountId: string, billId: string, bookmark: str
275275
}
276276
``` */}
277277

278-
### Start a Session from previous context (bookmark)
278+
### Start a session from previous context (bookmark)
279279

280-
To create a new Session from the context of a previous Session, pass a `bookmark` parameter to guarantee that the Session starts with a database version that is at least as up-to-date as the provided `bookmark`.
280+
To create a new session from the context of a previous session, pass a `bookmark` parameter to guarantee that the session starts with a database version that is at least as up-to-date as the provided `bookmark`.
281281

282282
```ts
283-
// retrieve bookmark from previous Session stored in HTTP header
283+
// retrieve bookmark from previous session stored in HTTP header
284284
const bookmark = request.headers.get('x-d1-bookmark') ?? 'first-unconstrained';
285285

286286
const session = env.DB.withSession(bookmark)
287287
const result = await session
288288
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
289289
.run()
290-
// store bookmark for a future Session
290+
// store bookmark for a future session
291291
response.headers.set('x-d1-bookmark', session.getBookmark() ?? "")
292292
```
293293

294-
- Starting a Session with a `bookmark` ensures the new Session will be at least as up-to-date as the previous Session that generated the given `bookmark`.
294+
- Starting a session with a `bookmark` ensures the new session will be at least as up-to-date as the previous session that generated the given `bookmark`.
295295
- Refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
296296

297297
{/* #### Example of using `bookmark`
@@ -443,7 +443,7 @@ With the REST API, set `read_replication.mode: disabled` to disable read replica
443443
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/).
444444

445445
:::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.
446+
Disabling read replication takes up to 24 hours until replicas to stop processing requests. Sessions API works with databases that do not have read replication enabled, so it is safe to run code with Sessions API even after disabling read replication.
447447
:::
448448

449449
<Tabs>
@@ -583,7 +583,7 @@ Sequential consistency has properties such as:
583583

584584
You may wish to refer to the following resources:
585585

586-
- Blog: [Beta announcement & technical deep dive](https://blog.cloudflare.com/d1-read-replication-beta/)
586+
- Blog: [Sequential consistency without borders: How D1 implements global read replication](https://blog.cloudflare.com/d1-read-replication-beta/)
587587
- Blog: [Building D1: a Global Database](https://blog.cloudflare.com/building-d1-a-global-database/)
588588
- [D1 Sessions API documentation](/d1/worker-api/d1-database#withsession)
589589
- [D1 Sessions API starter demo](https://github.com/cloudflare/templates/tree/staging/d1-starter-sessions-api)

src/content/glossary/d1.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ entries:
1515
a component in a database management system which takes a user query and generates the most efficient plan of executing that query (the query plan). For example, the query planner decides which indices to use, or which table to access first.
1616
- term: session
1717
general_definition: |-
18-
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.
18+
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.
1919
- term: bookmark
2020
general_definition: |-
2121
a bookmark represents the state of a database at a specific point in time.

0 commit comments

Comments
 (0)