To store data in worker KV namepace stably across concurrent requests

I am implementing logging logic in worker and created KV namespace for it.
I store stringified array and created this logic:

let array = await KV.get('key')
array = JSON.parse(array)
array.push({ 'somedata': 'data' })
await KV.put('key', array);

If there are at least 2 simultaneous requests to this worker and the first worker has already read the value (but did not write it yet) and the second one has read it, then the first worker put data, and the second rewrite it with his value and I lost the value from first worker.

I can implement logic to store every request data to the unique key (e.g. “keysFromWorkers:1”, “keysFromWorkers:2”, … )
But there are no Cloudflare API to get key-value pairs from KV namespace which I need.

"KV achieves this performance by being eventually-consistent. Changes are immediately visible in the edge location at which they are made, but may take up to 60 seconds to propagate to all other data centers. "

It is not the ideal solution for your task, you should use Durable Objects.

“Durable Objects provide low-latency coordination and consistent storage for the Workers platform through two features: global uniqueness and a transactional storage API.”


Are Durable Objects solve my problem and they will concatenate push operations for array or not?

A Durable Object is globally Unique, and the same way you wrote the code above, you can use the transactional storage API which provides strong consistency to store your key-value.

1 Like

OK, thanks.
But can I get/update/delete objects storages through the Cloudflare API ?
I didn’t find anything in docs