Skip to content

Commit 4beefe2

Browse files
thomasgauvinOxyjunhyperlint-ai[bot]
authored
thomasgauvin: add examples to workers kv (#20655)
* thomasgauvin: add examples to workers kv * Apply suggestions from code review Style guide alignment * Update src/content/docs/kv/examples/routing-with-workers-kv.mdx * Update src/content/docs/kv/examples/distributed-configuration-with-workers-kv.mdx * thomasgauvin: update caching with kv vs cache api * Update src/content/docs/kv/examples/cache-data-with-workers-kv.mdx Co-authored-by: hyperlint-ai[bot] <154288675+hyperlint-ai[bot]@users.noreply.github.com> * Update src/content/docs/kv/examples/cache-data-with-workers-kv.mdx * Update src/content/docs/kv/examples/cache-data-with-workers-kv.mdx --------- Co-authored-by: Jun Lee <[email protected]> Co-authored-by: hyperlint-ai[bot] <154288675+hyperlint-ai[bot]@users.noreply.github.com>
1 parent 586ad2f commit 4beefe2

File tree

7 files changed

+736
-270
lines changed

7 files changed

+736
-270
lines changed
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
---
2+
type: example
3+
summary: Cache data or API responses in Workers KV to improve application performance
4+
tags:
5+
- KV
6+
pcx_content_type: configuration
7+
title: Cache data with Workers KV
8+
sidebar:
9+
order: 5
10+
description: Example of how to use Workers KV to build a distributed application configuration store.
11+
---
12+
13+
import { Render, PackageManagers, Tabs, TabItem } from "~/components";
14+
15+
Workers KV can be used as a persistent, single, global cache accessible from Cloudflare Workers to speed up your application.
16+
Data cached in Workers KV is accessible from all other Cloudflare locations as well, and persists until expiry or deletion.
17+
18+
After fetching data from external resources in your Workers application, you can write the data to Workers KV.
19+
On subsequent Worker requests (in the same region or in other regions), you can read the cached data from Workers KV instead of calling the external API.
20+
This improves your Worker application's performance and resilience while reducing load on external resources.
21+
22+
This example shows how you can cache data in Workers KV and read cached data from Workers KV in a Worker application.
23+
24+
:::note[Note]
25+
26+
You can also cache data in Workers with the [Cache API](/workers/runtime-apis/cache/). With the Cache API,
27+
the contents of the cache do not replicate outside of the originating data center and the cache is ephemeral (can be evicted).
28+
29+
With Workers KV, the data is persisted by default to [central stores](/kv/concepts/how-kv-works/) (or can be set to [expire](/kv/api/write-key-value-pairs/#expiring-keys), and can be accessed from other Cloudflare locations.
30+
:::
31+
32+
## Cache data in Workers KV from your Worker application
33+
34+
In the following `index.ts` file, the Worker fetches data from an external server and caches the response in Workers KV. If the data is already cached in Workers KV, the Worker reads the cached data from Workers KV instead of calling the external API.
35+
36+
<Tabs>
37+
<TabItem label="index.ts">
38+
```js title="index.ts" collapse={42-1000}
39+
interface Env {
40+
CACHE_KV: KVNamespace;
41+
}
42+
43+
export default {
44+
async fetch(request, env, ctx): Promise<Response> {
45+
46+
const EXPIRATION_TTL = 60; // Cache expiration in seconds
47+
const url = 'https://example.com';
48+
const cacheKey = "cache-json-example";
49+
50+
// Try to get data from KV cache first
51+
let data = await env.CACHE_KV.get(cacheKey, { type: 'json' });
52+
let fromCache = true;
53+
54+
// If data is not in cache, fetch it from example.com
55+
if (!data) {
56+
console.log('Cache miss. Fetching fresh data from example.com');
57+
fromCache = false;
58+
59+
// In this example, we are fetching HTML content but it can also be API responses or any other data
60+
const response = await fetch(url);
61+
const htmlData = await response.text();
62+
63+
// In this example, we are converting HTML to JSON to demonstrate caching JSON data with Workers KV
64+
// You could cache any type of data, or even cache the HTML data directly
65+
data = helperConvertToJSON(htmlData);
66+
// The expirationTtl option is used to set the expiration time for the cache entry (in seconds), otherwise it will be stored indefinitely
67+
await env.CACHE_KV.put(cacheKey, JSON.stringify(data), { expirationTtl: EXPIRATION_TTL });
68+
}
69+
70+
// Return the appropriate response format
71+
return new Response(JSON.stringify({
72+
data,
73+
fromCache
74+
}), {
75+
headers: { 'Content-Type': 'application/json' }
76+
});
77+
78+
}
79+
} satisfies ExportedHandler<Env>;
80+
81+
// Helper function to convert HTML to JSON
82+
function helperConvertToJSON(html: string) {
83+
// Parse HTML and extract relevant data
84+
const title = helperExtractTitle(html);
85+
const content = helperExtractContent(html);
86+
const lastUpdated = new Date().toISOString();
87+
88+
return { title, content, lastUpdated };
89+
90+
}
91+
92+
// Helper function to extract title from HTML
93+
function helperExtractTitle(html: string) {
94+
const titleMatch = html.match(/<title>(.\*?)<\/title>/i);
95+
return titleMatch ? titleMatch[1] : 'No title found';
96+
}
97+
98+
// Helper function to extract content from HTML
99+
function helperExtractContent(html: string) {
100+
const bodyMatch = html.match(/<body>(.\*?)<\/body>/is);
101+
if (!bodyMatch) return 'No content found';
102+
103+
// Strip HTML tags for a simple text representation
104+
const textContent = bodyMatch[1].replace(/<[^>]*>/g, ' ')
105+
.replace(/\s+/g, ' ')
106+
.trim();
107+
108+
return textContent;
109+
110+
}
111+
112+
````
113+
</TabItem>
114+
<TabItem label="wrangler.jsonc">
115+
```json
116+
{
117+
"$schema": "node_modules/wrangler/config-schema.json",
118+
"name": "<ENTER_WORKER_NAME>",
119+
"main": "src/index.ts",
120+
"compatibility_date": "2025-03-03",
121+
"observability": {
122+
"enabled": true
123+
},
124+
"kv_namespaces": [
125+
{
126+
"binding": "CACHE_KV",
127+
"id": "<YOUR_BINDING_ID>"
128+
}
129+
]
130+
}
131+
````
132+
133+
</TabItem>
134+
</Tabs>
135+
136+
This code snippet demonstrates how to read and update cached data in Workers KV from your Worker.
137+
If the data is not in the Workers KV cache, the Worker fetches the data from an external server and caches it in Workers KV.
138+
139+
In this example, we convert HTML to JSON to demonstrate how to cache JSON data with Workers KV, but any type of data
140+
can be cached in Workers KV. For instance, you could cache API responses, HTML content, or any other data that you want to persist across requests.
141+
142+
## Related resources
143+
144+
- [Rust support in Workers](/workers/languages/rust/).
145+
- [Using KV in Workers](/kv/get-started/).
Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
---
2+
type: example
3+
summary: Use Workers KV to as a geo-distributed, low-latency configuration store for your Workers application
4+
tags:
5+
- KV
6+
pcx_content_type: configuration
7+
title: Build a distributed configuration store
8+
sidebar:
9+
order: 5
10+
description: Example of how to use Workers KV to build a distributed application configuration store.
11+
---
12+
13+
import { Render, PackageManagers, Tabs, TabItem } from "~/components";
14+
15+
Storing application configuration data is an ideal use case for Workers KV. Configuration data can include data to personalize an application for each user or tenant, enable features for user groups, restrict access with allow-lists/deny-lists, etc. These use-cases can have high read volumes that are highly cacheable by Workers KV, which can ensure low-latency reads from your Workers application.
16+
17+
In this example, application configuration data is used to personalize the Workers application for each user. The configuration data is stored in an external application and database, and written to Workers KV using the REST API.
18+
19+
## Write your configuration from your external application to Workers KV
20+
21+
In some cases, your source-of-truth for your configuration data may be stored elsewhere than Workers KV.
22+
If this is the case, use the Workers KV REST API to write the configuration data to your Workers KV namespace.
23+
24+
The following external Node.js application demonstrates a simple scripts that reads user data from a database and writes it to Workers KV using the REST API library.
25+
26+
<Tabs>
27+
<TabItem label="index.js">
28+
```js title="index.js"
29+
const postgres = require('postgres');
30+
const { Cloudflare } = require('cloudflare');
31+
const { backOff } = require('exponential-backoff');
32+
33+
if(!process.env.DATABASE_CONNECTION_STRING || !process.env.CLOUDFLARE_EMAIL || !process.env.CLOUDFLARE_API_KEY || !process.env.CLOUDFLARE_WORKERS_KV_NAMESPACE_ID || !process.env.CLOUDFLARE_ACCOUNT_ID) {
34+
console.error('Missing required environment variables.');
35+
process.exit(1);
36+
}
37+
38+
// Setup Postgres connection
39+
const sql = postgres(process.env.DATABASE_CONNECTION_STRING);
40+
41+
// Setup Cloudflare REST API client
42+
const client = new Cloudflare({
43+
apiEmail: process.env.CLOUDFLARE_EMAIL,
44+
apiKey: process.env.CLOUDFLARE_API_KEY,
45+
});
46+
47+
// Function to sync Postgres data to Workers KV
48+
async function syncPreviewStatus() {
49+
console.log('Starting sync of user preview status...');
50+
51+
try {
52+
// Get all users and their preview status
53+
const users = await sql`SELECT id, preview_features_enabled FROM users`;
54+
55+
console.log(users);
56+
57+
// Create the bulk update body
58+
const bulkUpdateBody = users.map(user => ({
59+
key: user.id,
60+
value: JSON.stringify({
61+
preview_features_enabled: user.preview_features_enabled
62+
})
63+
}));
64+
65+
const response = await backOff(async () => {
66+
console.log("trying to update")
67+
try{
68+
const response = await client.kv.namespaces.bulkUpdate(process.env.CLOUDFLARE_WORKERS_KV_NAMESPACE_ID, {
69+
account_id: process.env.CLOUDFLARE_ACCOUNT_ID,
70+
body: bulkUpdateBody
71+
});
72+
}
73+
catch(e){
74+
// Implement your error handling and logging here
75+
console.log(e);
76+
throw e; // Rethrow the error to retry
77+
}
78+
});
79+
80+
console.log(`Sync complete. Updated ${users.length} users.`);
81+
} catch (error) {
82+
console.error('Error syncing preview status:', error);
83+
}
84+
}
85+
86+
// Run the sync function
87+
syncPreviewStatus()
88+
.catch(console.error)
89+
.finally(() => process.exit(0));
90+
```
91+
</TabItem>
92+
<TabItem label=".env">
93+
```md title=".env"
94+
DATABASE_CONNECTION_STRING = <DB_CONNECTION_STRING_HERE>
95+
CLOUDFLARE_EMAIL = <CLOUDFLARE_EMAIL_HERE>
96+
CLOUDFLARE_API_KEY = <CLOUDFLARE_API_KEY_HERE>
97+
CLOUDFLARE_ACCOUNT_ID = <CLOUDFLARE_ACCOUNT_ID_HERE>
98+
CLOUDFLARE_WORKERS_KV_NAMESPACE_ID = <CLOUDFLARE_WORKERS_KV_NAMESPACE_ID_HERE>
99+
````
100+
101+
</TabItem>
102+
<TabItem label="db.sql">
103+
```sql title="db.sql"
104+
-- Create users table with preview_features_enabled flag
105+
CREATE TABLE users (
106+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
107+
username VARCHAR(100) NOT NULL,
108+
email VARCHAR(255) NOT NULL,
109+
preview_features_enabled BOOLEAN DEFAULT false
110+
);
111+
112+
-- Insert sample users
113+
INSERT INTO users (username, email, preview_features_enabled) VALUES
114+
('alice', '[email protected]', true),
115+
('bob', '[email protected]', false),
116+
('charlie', '[email protected]', true);
117+
118+
````
119+
</TabItem>
120+
</Tabs>
121+
122+
In this code snippet, the Node.js application reads user data from a Postgres database and writes the user data to be used for configuration in our Workers application to Workers KV using the Cloudflare REST API Node.js library.
123+
The application also uses exponential backoff to handle retries in case of errors.
124+
125+
## Use configuration data from Workers KV in your Worker application
126+
127+
With the configuration data now in the Workers KV namespace, we can use it in our Workers application to personalize the application for each user.
128+
129+
<Tabs>
130+
<TabItem label="index.ts">
131+
```js title="index.ts"
132+
// Example configuration data stored in Workers KV:
133+
// Key: "user-id-abc" | Value: {"preview_features_enabled": false}
134+
// Key: "user-id-def" | Value: {"preview_features_enabled": true}
135+
136+
interface Env {
137+
USER_CONFIGURATION: KVNamespace;
138+
}
139+
140+
export default {
141+
async fetch(request, env) {
142+
// Get user ID from query parameter
143+
const url = new URL(request.url);
144+
const userId = url.searchParams.get('userId');
145+
146+
if (!userId) {
147+
return new Response('Please provide a userId query parameter', {
148+
status: 400,
149+
headers: { 'Content-Type': 'text/plain' }
150+
});
151+
}
152+
153+
154+
const userConfiguration = await env.USER_CONFIGURATION.get<{
155+
preview_features_enabled: boolean;
156+
}>(userId, {type: "json"});
157+
158+
console.log(userConfiguration);
159+
160+
// Build HTML response
161+
const html = `
162+
<!DOCTYPE html>
163+
<html>
164+
<head>
165+
<title>My App</title>
166+
<style>
167+
body {
168+
font-family: Arial, sans-serif;
169+
max-width: 800px;
170+
margin: 0 auto;
171+
padding: 20px;
172+
}
173+
.preview-banner {
174+
background-color: #ffeb3b;
175+
padding: 10px;
176+
text-align: center;
177+
margin-bottom: 20px;
178+
border-radius: 4px;
179+
}
180+
</style>
181+
</head>
182+
<body>
183+
${userConfiguration?.preview_features_enabled ? `
184+
<div class="preview-banner">
185+
🎉 You have early access to preview features! 🎉
186+
</div>
187+
` : ''}
188+
<h1>Welcome to My App</h1>
189+
<p>This is the regular content everyone sees.</p>
190+
</body>
191+
</html>
192+
`;
193+
194+
return new Response(html, {
195+
headers: { "Content-Type": "text/html; charset=utf-8" }
196+
});
197+
}
198+
} satisfies ExportedHandler<Env>;
199+
200+
```
201+
</TabItem>
202+
<TabItem label="wrangler.jsonc">
203+
```json
204+
{
205+
"$schema": "node_modules/wrangler/config-schema.json",
206+
"name": "<ENTER_WORKER_NAME>",
207+
"main": "src/index.ts",
208+
"compatibility_date": "2025-03-03",
209+
"observability": {
210+
"enabled": true
211+
},
212+
"kv_namespaces": [
213+
{
214+
"binding": "USER_CONFIGURATION",
215+
"id": "<YOUR_BINDING_ID>"
216+
}
217+
]
218+
}
219+
````
220+
221+
</TabItem>
222+
</Tabs>
223+
224+
This code will use the path within the URL and find the file associated to the path within the KV store. It also sets the proper MIME type in the response to inform the browser how to handle the response. To retrieve the value from the KV store, this code uses `arrayBuffer` to properly handle binary data such as images, documents, and video/audio files.
225+
226+
## Optimize performance for configuration
227+
228+
To optimize performance, you may opt to consolidate values in fewer key-value pairs. By doing so, you may benefit from higher caching efficiency and lower latency.
229+
230+
For example, instead of storing each user's configuration in a separate key-value pair, you may store all users' configurations in a single key-value pair. This approach may be suitable for use-cases where the configuration data is small and can be easily managed in a single key-value pair (the [size limit for a Workers KV value is 25 MiB](/kv/platform/limits/)).
231+
232+
## Related resources
233+
234+
- [Rust support in Workers](/workers/languages/rust/)
235+
- [Using KV in Workers](/kv/get-started/)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
type: example
3+
summary: Use Workers KV to store A/B testing configuration data and analyze the performance of different versions of your website
4+
tags:
5+
- KV
6+
pcx_content_type: configuration
7+
title: A/B testing with Workers KV
8+
external_link: /reference-architecture/diagrams/serverless/a-b-testing-using-workers/
9+
sidebar:
10+
order: 6
11+
---

0 commit comments

Comments
 (0)