Starter repository using Cloudflare Workers with D1 database and the new D1 Sessions API for read replication.
This demo simulates purchase orders administration. There are two main actions you can do.
- Create an order with a
customerId,orderId, andquantity. - List all orders.
The UI when visiting the deployed Worker project shows 3 buttons.
- Create order & List
- Creates a new order using the provided customer ID with a random order ID and quantity.
- Does a
POST /api/ordersrequest to the Worker, and its handler uses the Sessions API to do anINSERTfirst for the new order that will be forwarded to the primary database instance, followed by aSELECTquery to list all orders that will be executed by nearest replica database.
- List orders
- Lists every order recorded in the database.
- Does a
GET /api/ordersrequest to the Worker, and its handler uses the Sessions API to do aSELECTquery to list the orders that will be executed by the nearest replica database.
- Reset
- Drops and recreates the orders table.
- Gets executed by the primary database.
The UI JavaScript code maintains the latest bookmark returned by the API and sends it along every subsequent request.
This ensures that we have sequential consistency in our observed database results and all our actions are properly ordered.
Read more information about how the Sessions API works, and how sequential consistency is achieved in the [D1 read replication documentation](https://developers.cloudflare.com/d1/best-practices/read-replication/.
- Checkout the project locally.
- Run
npm cito install all dependencies. - Run
npm run deployto deploy to your Cloudflare account. - Visit the URL you got in step 3.
- Run
npm run devto start the development server. - Visit http://localhost:8787.
Note: The "Served by Region" information won't be shown when running locally.