Skip to content

Commit 1dbf2de

Browse files
teresalvesOxyjunthomasgauvin
authored
KV: add bulk gets documentation (#21392)
* KV: add bulk gets documentation * PCX review * Update src/content/docs/kv/api/read-key-value-pairs.mdx * Update src/content/docs/kv/api/read-key-value-pairs.mdx * Update src/content/docs/kv/api/read-key-value-pairs.mdx * Update src/content/docs/kv/api/read-key-value-pairs.mdx * Update src/content/docs/kv/api/read-key-value-pairs.mdx * checking perms * wip * fix: delete changes to settings.json file * adjust changelog * Update .vscode/settings.json * fix styling, missing differentiation between h4 and h5 * Update src/content/changelog/kv/2025-04-10-kv-bulk-reads.mdx --------- Co-authored-by: talves <[email protected]> Co-authored-by: Jun Lee <[email protected]> Co-authored-by: Thomas Gauvin <[email protected]> Co-authored-by: Thomas Gauvin <[email protected]>
1 parent 44aebde commit 1dbf2de

File tree

3 files changed

+151
-38
lines changed

3 files changed

+151
-38
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
title: Read multiple keys from Workers KV with bulk reads
3+
description: You can now retrieve up to 100 keys in a single bulk read request to Workers KV.
4+
products:
5+
- kv
6+
date: 2025-04-17T14:00:00Z
7+
---
8+
9+
You can now retrieve up to 100 keys in a single bulk read request made to Workers KV using the binding.
10+
11+
This makes it easier to request multiple KV pairs within a single Worker invocation. Retrieving many key-value pairs using the bulk read operation is more performant than making individual requests since bulk read operations are not affected by [Workers simultaneous connection limits](/workers/platform/limits/#simultaneous-open-connections).
12+
```js
13+
// Read single key
14+
const key = "key-a";
15+
const value = await env.NAMESPACE.get(keys);
16+
17+
// Read multiple keys
18+
const keys = ["key-a", "key-b", "key-c", ...] // up to 100 keys
19+
const values : Map<string, string?> = await env.NAMESPACE.get(keys);
20+
21+
// Print the value of "key-a" to the console.
22+
console.log(`The first key is ${values.get("key-a")}.`)
23+
```
24+
25+
Consult the [Workers KV Read key-value pairs API](/kv/api/read-key-value-pairs/) for full details on Workers KV's new bulk reads support.

src/content/docs/kv/api/read-key-value-pairs.mdx

Lines changed: 125 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -8,52 +8,81 @@ sidebar:
88
To get the value for a given key, call the `get()` method of the [KV binding](/kv/concepts/kv-bindings/) on any [KV namespace](/kv/concepts/kv-namespaces/) you have bound to your Worker code:
99

1010
```js
11+
// Read individual key
1112
env.NAMESPACE.get(key);
13+
14+
// Read multiple keys
15+
env.NAMESPACE.get(keys);
1216
```
1317

14-
The `get()` method returns a promise you can `await` on to get the value. If the key is not found, the promise will resolve with the literal value `null`.
18+
The `get()` method returns a promise you can `await` on to get the value.
1519

16-
#### Example
20+
If you request a single key as a string, you will get a single response in the promise. If the key is not found, the promise will resolve with the literal value `null`.
1721

18-
An example of reading a key from within a Worker:
22+
You can also request an array of keys. The return value with be a `Map` of the key-value pairs found,
23+
with keys not found having `null` values.
1924

2025
```js
2126
export default {
2227
async fetch(request, env, ctx) {
2328
try {
29+
// Read single key, returns value or null
2430
const value = await env.NAMESPACE.get("first-key");
2531

26-
if (value === null) {
27-
return new Response("Value not found", { status: 404 });
28-
}
29-
return new Response(value);
32+
// Read multiple keys, returns Map of values
33+
const values = await env.NAMESPACE.get(["first-key", "second-key"]);
34+
35+
// Read single key with metadata, returns value or null
36+
const valueWithMetadata = await env.NAMESPACE.getWithMetadata("first-key");
37+
38+
// Read multiple keys with metadata, returns Map of values
39+
const valuesWithMetadata = await env.NAMESPACE.getWithMetadata(["first-key", "second-key"]);
40+
41+
return new Response({
42+
value: value,
43+
values: Object.fromEntries(values),
44+
valueWithMetadata: valueWithMetadata,
45+
valuesWithMetadata: Object.fromEntries(valuesWithMetadata)
46+
});
3047
} catch (e) {
3148
return new Response(e.message, { status: 500 });
3249
}
3350
},
3451
};
3552
```
3653

54+
:::note
55+
56+
`get()` and `getWithMetadata()` methods may return stale values. If a given key has recently been read in a given location, writes or updates to the key made in other locations may take up to 60 seconds (or the duration of the `cacheTtl`) to display.
57+
58+
:::
59+
60+
3761
## Reference
3862

3963
The following methods are provided to read from KV:
4064

41-
- [get()](#get-method)
42-
- [getWithMetadata()](#getwithmetadata-method)
65+
- [get()](#request-a-single-key-with-getkey-string)
66+
- [getWithMetadata()](#request-multiple-keys-with-getkeys-string)
4367

4468
### `get()` method
4569

46-
To get the value for a given key, call the `get()` method on any KV namespace you have bound to your Worker code:
70+
Use the `get()` method to get a single value, or multiple values if given multiple keys:
71+
72+
- Read single keys with [get(key: string)](#request-a-single-key-with-getkey-string)
73+
- Read multiple keys with [get(keys: string[])](#request-multiple-keys-with-getkeys-string)
74+
75+
#### Request a single key with `get(key: string)`
76+
77+
To get the value for a single key, call the `get()` method on any KV namespace you have bound to your Worker code with:
4778

4879
```js
4980
env.NAMESPACE.get(key, type?);
5081
// OR
5182
env.NAMESPACE.get(key, options?);
5283
```
5384
54-
The `get()` method returns a promise you can `await` on to get the value. If the key is not found, the promise will resolve with the literal value `null`.
55-
56-
#### Parameters
85+
##### Parameters
5786
5887
- `key`: `string`
5988
- The key of the KV pair.
@@ -65,7 +94,7 @@ The `get()` method returns a promise you can `await` on to get the value. If the
6594
}`
6695
- Optional. Object containing the optional `cacheTtl` and `type` properties. The `cacheTtl` property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). The `type` property defines the type of the value to be returned.
6796
68-
#### Response
97+
##### Response
6998
7099
- `response`: `Promise<string | Object | ArrayBuffer | ReadableStream | null>`
71100
- The value for the requested KV pair. The response type will depend on the `type` parameter provided for the `get()` command as follows:
@@ -74,10 +103,52 @@ The `get()` method returns a promise you can `await` on to get the value. If the
74103
- `arrayBuffer`: An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance.
75104
- `stream`: A [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).
76105
77-
The `get()` method may return stale values. If a given key has recently been read in a given location, writes or updates to the key made in other locations may take up to 60 seconds (or the duration of the `cacheTtl`) to display.
106+
#### Request multiple keys with `get(keys: string[])`
107+
108+
To get the values for multiple keys, call the `get()` method on any KV namespace you have bound to your Worker code with:
109+
110+
```js
111+
env.NAMESPACE.get(keys, type?);
112+
// OR
113+
env.NAMESPACE.get(keys, options?);
114+
```
115+
116+
##### Parameters
117+
118+
- `keys`: `string[]`
119+
- The keys of the KV pairs. Max: 100 keys
120+
- `type`: `"text" | "json"`
121+
- Optional. The type of the value to be returned. `text` is the default.
122+
- `options`: `{
123+
cacheTtl?: number,
124+
type?: "text" | "json"
125+
}`
126+
- Optional. Object containing the optional `cacheTtl` and `type` properties. The `cacheTtl` property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). The `type` property defines the type of the value to be returned.
127+
128+
:::note
129+
130+
The `.get()` function to read multiple keys does not support `arrayBuffer` or `stream` return types. If you need to read multiple keys of `arrayBuffer` or `stream` types, consider using the `.get()` function to read individual keys in parallel with `Promise.all()`.
131+
132+
:::
133+
134+
##### Response
135+
136+
- `response`: `Promise<Map<string, string | Object | null>>`
137+
- The value for the requested KV pair. If no key is found, `null` is returned for the key. The response type will depend on the `type` parameter provided for the `get()` command as follows:
138+
- `text`: A `string` (default).
139+
- `json`: An object decoded from a JSON string.
140+
141+
The limit of the response size is 25 MB. Responses above this size will fail with a `413 Error` error message.
78142
79143
### `getWithMetadata()` method
80144
145+
Use the `getWithMetadata()` method to get a single value along with its metadata, or multiple values with their metadata:
146+
147+
- Read single keys with [getWithMetadata(key: string)](#request-a-single-key-with-getwithmetadatakey-string)
148+
- Read multiple keys with [getWithMetadata(keys: string[])](#request-multiple-keys-with-getwithmetadatakeys-string)
149+
150+
#### Request a single key with `getWithMetadata(key: string)`
151+
81152
To get the value for a given key along with its metadata, call the `getWithMetadata()` method on any KV namespace you have bound to your Worker code:
82153
83154
```js
@@ -88,7 +159,7 @@ env.NAMESPACE.getWithMetadata(key, options?);
88159
89160
Metadata is a serializable value you append to each KV entry.
90161
91-
#### Parameters
162+
##### Parameters
92163
93164
- `key`: `string`
94165
- The key of the KV pair.
@@ -100,7 +171,7 @@ Metadata is a serializable value you append to each KV entry.
100171
}`
101172
- Optional. Object containing the optional `cacheTtl` and `type` properties. The `cacheTtl` property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). The `type` property defines the type of the value to be returned.
102173
103-
#### Response
174+
##### Response
104175
105176
- `response`: `Promise<{
106177
value: string | Object | ArrayBuffer | ReadableStream | null,
@@ -115,30 +186,48 @@ metadata: string | null
115186
116187
If there is no metadata associated with the requested key-value pair, `null` will be returned for metadata.
117188
118-
The `getWithMetadata()` method may return stale values. If a given key has recently been read in a given location, writes or updates to the key made in other locations may take up to 60 seconds (or the duration of the `cacheTtl`) to display.
189+
#### Request multiple keys with `getWithMetadata(keys: string[])`
119190
120-
#### Example
121-
122-
An example of reading a key with metadata from within a Worker:
191+
To get the values for a given set of keys along with their metadata, call the `getWithMetadata()` method on any KV namespace you have bound to your Worker code with:
123192
124193
```js
125-
export default {
126-
async fetch(request, env, ctx) {
127-
try {
128-
const { value, metadata } =
129-
await env.NAMESPACE.getWithMetadata("first-key");
130-
131-
if (value === null) {
132-
return new Response("Value not found", { status: 404 });
133-
}
134-
return new Response(value);
135-
} catch (e) {
136-
return new Response(e.message, { status: 500 });
137-
}
138-
},
139-
};
194+
env.NAMESPACE.getWithMetadata(keys, type?);
195+
// OR
196+
env.NAMESPACE.getWithMetadata(keys, options?);
140197
```
141198
199+
##### Parameters
200+
201+
- `keys`: `string[]`
202+
- The keys of the KV pairs. Max: 100 keys
203+
- `type`: `"text" | "json"`
204+
- Optional. The type of the value to be returned. `text` is the default.
205+
- `options`: `{
206+
cacheTtl?: number,
207+
type?: "text" | "json"
208+
}`
209+
- Optional. Object containing the optional `cacheTtl` and `type` properties. The `cacheTtl` property defines the length of time in seconds that a KV result is cached in the global network location it is accessed from (minimum: 60). The `type` property defines the type of the value to be returned.
210+
211+
:::note
212+
The `.get()` function to read multiple keys does not support `arrayBuffer` or `stream` return types. If you need to read multiple keys of `arrayBuffer` or `stream` types, consider using the `.get()` function to read individual keys in parallel with `Promise.all()`.
213+
:::
214+
215+
##### Response
216+
217+
- `response`: `Promise<Map<string, {
218+
value: string | Object | null,
219+
metadata: string | Object | null
220+
}>`
221+
222+
- An object containing the value and the metadata for the requested KV pair. The type of the value attribute will depend on the `type` parameter provided for the `getWithMetadata()` command as follows:
223+
- `text`: A `string` (default).
224+
- `json`: An object decoded from a JSON string.
225+
- The type of the metadata will just depend on what is stored, which can be either a string or an object.
226+
227+
If there is no metadata associated with the requested key-value pair, `null` will be returned for metadata.
228+
229+
The limit of the response size is 25 MB. Responses above this size will fail with a `413 Error` error message.
230+
142231
## Guidance
143232
144233
### Type parameter
@@ -167,4 +256,3 @@ The effective `cacheTtl` of an already cached item can be reduced by getting it
167256
## Other methods to access KV
168257
169258
You can [read key-value pairs from the command line with Wrangler](/kv/reference/kv-commands/#kv-key-get) and [from the REST API](/api/resources/kv/subresources/namespaces/subresources/values/methods/get/).
170-

src/styles/headings.css

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
:root {
2-
--sl-text-h4: var(--sl-text-base);
2+
--sl-text-h4: var(--sl-text-lg);
33
--sl-text-h5: var(--sl-text-base);
44
}

0 commit comments

Comments
 (0)